我正在尝试创建以下结构: [StructLayout(LayoutKind.Explicit, Size=14)] public struct Message { [FieldOffset(0)] public ushort X; [FieldOffset(2)] [MarshalAs(UnmanagedType.ByValArray, SizeConst=5)] private ushort[] Y; [FieldOffset
[StructLayout(LayoutKind.Explicit, Size=14)] public struct Message { [FieldOffset(0)] public ushort X; [FieldOffset(2)] [MarshalAs(UnmanagedType.ByValArray, SizeConst=5)] private ushort[] Y; [FieldOffset(12)] public ushort Z; }
我收到以下错误:
无法从程序集中加载“消息”类型,因为它包含偏移4处的对象字段,该字段未正确对齐或由非对象字段重叠.
有谁知道为什么这会导致错误?
注意:我不能使用Pack因为我正在使用紧凑的框架.
谢谢.
您可以在此示例中看到该行为:
[StructLayout(LayoutKind.Explicit, Size = 14)] public struct Message { [FieldOffset(0)] public ushort X; [FieldOffset(2)] private ushort Y1; [MarshalAs(UnmanagedType.LPArray)] [FieldOffset(4)] private ushort[] Y2; [FieldOffset(12)] public ushort Z; }
对于这种类型的结构,我从不让编组人员试图处理每个成员.结构很小,所以打破每个单独的项目,如下所示:
[StructLayout(LayoutKind.Explicit, Size = 14)] public struct Message { [FieldOffset(0)] public ushort X; [FieldOffset(2)] private ushort Y1; [FieldOffset(4)] private ushort Y2; [FieldOffset(6)] private ushort Y3; [FieldOffset(8)] private ushort Y4; [FieldOffset(10)] private ushort Y5; [FieldOffset(12)] public ushort Z; }
或使用这样的模拟“联合”:
public struct Y { public ushort a; public ushort b; public ushort c; public ushort d; public ushort e; } [StructLayout(LayoutKind.Explicit, Size = 14)] public struct Message { [FieldOffset(0)] public ushort X; [FieldOffset(2)] private Y Y; [FieldOffset(12)] public ushort Z; }