![](/img/trans.png)
[英]C# object initializer will initialize read only properties, but for non-primitive types only
[英]Alignment error recreating C++ union type with non-primitive types in C#
我在C ++中有一个简单的联合体(字节数组和一个短整数),试图将其移植到C#并Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.
联合体Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.
我怀疑我的实现无法正常工作,因为我将数组作为结构成员之一。
现有的C ++联合:
union {
char c[2];
short data;
} u;
尝试C#实现:
[StructLayout(LayoutKind.Explicit, Size =2)]
public struct Union
{
[MarshalAs(UnmanagedType.LPArray)]
[FieldOffset(0)]
public byte[] c;
[FieldOffset(0)]
public short data;
}
之前回答过类似的问题,但它似乎仅适用于原始类型: C#中的C ++联合
先感谢您。
您是否尝试过“ StructLayout(LayoutKind.Explicit,Size = 2,Pack = 1)”? C#似乎有问题,默认为4字节打包大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.