Given a struct MyStruct
, I can get the size of instances of that struct using sizeof(MyStruct)
in unsafe code. However, I want to get the size of a struct given the Type
object for the struct, ie, sizeof(typeof(MyStruct))
. There is Marshal.SizeOf
, but that returns the unmanaged marshalled size, whereas I want the managed size of that struct.
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
The size of int is 4 bytes and the struct node *link; is also 4 bytes.
The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.
There is no documented way to discover the layout of a managed struct. The JIT compiler takes readily advantage of this, it will reorder fields of the struct to get the best packing. Marshaling is always required to get a predictable layout, as directed by the [StructLayout]
attribute. You have to jump through the Marshal.StructureToPtr()
hoop. Whether you do it yourself or let the pinvoke marshaller do it for you.
Marshal.SizeOf(Type)
gives you the size of the marshaled struct
. More background on why it works this way is available in this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With