thecoop
thecoop

Reputation: 46158

Get the sizeof a struct given the System.Type

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.

Upvotes: 8

Views: 5852

Answers (1)

Hans Passant
Hans Passant

Reputation: 942408

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.

Upvotes: 7

Related Questions