[英]Alignment error recreating C++ union type with non-primitive types in C#
I have a simple union (byte array and a short) in C++ which I am attempting to port to C# and getting 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 ++中有一个简单的联合体(字节数组和一个短整数),试图将其移植到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.
I suspect that my implementation doesn't work because I have array as one of the struct members. 我怀疑我的实现无法正常工作,因为我将数组作为结构成员之一。
existing C++ union: 现有的C ++联合:
union {
char c[2];
short data;
} u;
attempted C# implementation: 尝试C#实现:
[StructLayout(LayoutKind.Explicit, Size =2)]
public struct Union
{
[MarshalAs(UnmanagedType.LPArray)]
[FieldOffset(0)]
public byte[] c;
[FieldOffset(0)]
public short data;
}
similar question was answered before but it seems to work only for primitive types: C++ union in C# 之前回答过类似的问题,但它似乎仅适用于原始类型: C#中的C ++联合
Thank you in advance. 先感谢您。
Have you tried "StructLayout(LayoutKind.Explicit, Size =2, Pack=1)"? 您是否尝试过“ StructLayout(LayoutKind.Explicit,Size = 2,Pack = 1)”? Seems to be a problem with C# default to a 4-byte packing size.
C#似乎有问题,默认为4字节打包大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.