Get the sizeof a struct given the System.Type

前端 未结 1 1859
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 07:10

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

相关标签:
1条回答
  • 2021-01-05 08:04

    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.

    0 讨论(0)
提交回复
热议问题