什么时候应该明确指定StructLayout? [英] When should I explicitly specify a StructLayout?

查看:56
本文介绍了什么时候应该明确指定StructLayout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想从C#调用DLL,并且遇到了定义我自己的结构的需要.许多文章强制使用

I'm fiddling with calling DLLs from C#, and came across the need to define my own structs. Lots of articles force a sequential layout for the struct with

[StructLayout(LayoutKind.Sequential)]
struct Foo ...

因此,我遵循了套件,并且程序正常运行.现在,当我将线路拔出时,它仍然有效.我为什么需要它?

So, I followed suite, and my programme worked. Now, when I took the line out, it still works. Why do I need it?

推荐答案

受管结构的内部布局是无记录的,也是无法发现的.诸如会员订购和包装之类的实现细节被有意地隐藏了.使用[StructLayout]属性,您可以强制P/Invoke编组器施加特定的布局和包装.

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.

默认值恰好与您使代码正常工作所需的匹配只是偶然.虽然不是不常见的一种.请注意Type.StructLayoutAttribute属性.

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.

这篇关于什么时候应该明确指定StructLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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