When should I explicitly specify a StructLayout?

試著忘記壹切 提交于 2019-12-01 17:14:32

The internal layout of a managed struct is undocumented and undiscoverable. Implementation details like member order and packing are intentionally hidden. With the [StructLayout] attribute, you force the P/Invoke marshaller to impose a specific layout and packing.

That the default just happens to match what you need to get your code to work is merely an accident. Although not an uncommon one. Note the Type.StructLayoutAttribute property.

Interesting point. I'm sure I had code that failed until I put in an explicit LayoutKind.Sequential, however I have confirmed Sequential is the default for structures even in 1.1.

Note the VB Reference for Structure implies at Remarks > Behaviour > Memory Consumption that you do need to specify StructLayout to confirm the memory layout, but the documentation for StructLayoutAttribute states Sequential is the default for structures in Microsoft compilers.

I am not entirely sure, but it may affect binary serialization - it might spit out the fields in order with not naming or ordering information (resulting in a smaller file), but that is a complete whim.

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