获取给定 System.Type 的结构的大小
给定一个结构 MyStruct
,我可以在不安全代码中使用 sizeof(MyStruct)
获取该结构实例的大小。但是,我想在给定结构体的 Type
对象的情况下获取结构体的大小,即 sizeof(typeof(MyStruct))
。有 Marshal.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有记录的方法来发现托管结构的布局。 JIT 编译器很容易利用这一点,它将重新排序结构的字段以获得最佳打包。按照
[StructLayout]
属性的指示,始终需要编组来获得可预测的布局。您必须跳过Marshal.StructureToPtr()
这一环。无论您自己做还是让 pinvoke marshaller 为您做。Marshal.SizeOf(Type)
为您提供封送的struct
的大小。有关其工作原理的更多背景信息,请参阅 这个答案。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 theMarshal.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 marshaledstruct
. More background on why it works this way is available in this answer.