Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sizeof a struct given the System.Type

Tags:

c#

.net

sizeof

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.

like image 223
thecoop Avatar asked Dec 17 '10 16:12

thecoop


People also ask

How do you determine the size of a 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.

Can you use sizeof on a struct?

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.

What is the size of struct node?

The size of int is 4 bytes and the struct node *link; is also 4 bytes.

How big is a struct C?

The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.


1 Answers

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.

like image 179
Hans Passant Avatar answered Oct 04 '22 20:10

Hans Passant