获取sizeof的一个结构给出的System.Type [英] Get the sizeof a struct given the System.Type

查看:182
本文介绍了获取sizeof的一个结构给出的System.Type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个结构 MYSTRUCT ,我可以使用的sizeof(MYSTRUCT)在该结构的实例大小不安全code。不过,我想给出一个结构的大小键入对象的结构,即的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.

推荐答案

有没有记录的方式来发现有管理的结构布局。 JIT编译器利用了这个很容易的优势,这将重新排序结构的领域,以获得最佳的包装。封送处理是的总是的获得predictable布局,所指示的 [StructLayout] 属性要求。你必须跳通过 Marshal.StructureToPtr()箍。无论你做你自己或让PInvoke的编组为您代劳。

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(类型)给你的尺寸的封结构。更多的背景,为什么是这样工作是在<一个可用href="http://stackoverflow.com/questions/3361986/how-to-check-the-number-of-bytes-consumed-by-my-structure/3362736#3362736">this回答。

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

这篇关于获取sizeof的一个结构给出的System.Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆