与顺序布局和显式布局相比,StructLayout.Auto 意味着什么?
我认为LayoutKind.Sequential和LayoutKind.Explicit很清楚,但是C#如何处理LayoutKind.Auto?
I think LayoutKind.Sequential and LayoutKind.Explicit are clear, but how is LayoutKind.Auto handled by C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
LayoutKind.Auto
只是意味着“我授予 CLR 重新排序与这些字段对应的字节的权限”。它准确地决定如何重新组织内存使用、打包等字段。文档中没有指定具体会进行哪些更改,可能是因为它是与您编写结构的方式无关的实现细节。如果您传递给非托管代码,这总是一件坏事,因为非托管代码期望这些字段按特定顺序排列。它们可能的重新排列必然会产生意想不到的后果。这就是为什么您不能将 LayoutKind.Auto 结构公开给非托管代码的原因。
LayoutKind.Auto
just means, "I give the CLR permission to reorder the bytes corresponding to these fields". It decides exactly how to reorganize the fields for memory usage, packing, et cetera. Exactly which changes it will make isn't specified by the documentation, probably because it's an implementation detail that isn't relevant to how you write your structs.This is invariably a bad thing if you're passing to unmanaged code, because unmanaged code expects those fields to be in a particular order. Their possible rearrangement is bound to have unintended consequences. That's why you can't expose
LayoutKind.Auto
structs to unmanaged code.文档似乎很清楚:
换句话说,布局是动态的,意味着您的对象不能再在托管代码之外使用。
The documentation seems pretty clear:
In other words, the layout is dynamic and means that your object can no longer be used outside of Managed Code.
MS 说这里
MS says here
运行时会自动为对象的成员选择适当的布局在非托管内存中。
The runtime automatically chooses an appropriate layout for the members of an object in unmanaged memory.