Get the sizeof a struct given the System.Type

人走茶凉 提交于 2019-11-30 05:17:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4472465/get-the-sizeof-a-struct-given-the-system-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!