我在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.
,我怀疑我的实现无法正常工作,因为我将数组作为结构之一成员。
现有的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++ union in C#
谢谢。
答案 0 :(得分:0)
您是否尝试过“ StructLayout(LayoutKind.Explicit,Size = 2,Pack = 1)”?似乎C#的问题默认为4字节打包大小。