Get structure size based on System.Type

Given struct MyStruct , I can get the size of the instances of this structure using sizeof(MyStruct) in insecure code. However, I want to get the size of the structure specified for the Type object for the structure, i.e. sizeof(typeof(MyStruct)) . There is Marshal.SizeOf , but returns an unmanaged marshalling size, whereas I want a controlled size of this structure.

+6
c # sizeof
source share
1 answer

There is no documented way to discover a mock managed structure. The JIT compiler easily uses this; it will reorder the fields of the structure to get better packaging. Marshaling should always get a predictable layout, as indicated by the [StructLayout] . You have to jump through the Marshal.StructureToPtr() hoop. Regardless of whether you do it yourself or let the pinvoke Marxiller do it for you.

Marshal.SizeOf(Type) gives the size of the struct marshaling. More information on why it works this way is available in this answer .

+4
source share

All Articles