CF Marshaler 在这种类型的事情上不太擅长,并且您正在尝试的内容不受支持。问题是它知道第一个元素是未对齐的,但它似乎不明白数组中的每个元素也将是未对齐的。
您可以在此示例中看到该行为有效:
[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;
}
对于这种类型的结构,无论如何我从不让 marshaler 尝试处理每个成员。结构很小,所以像这样分解每个单独的项目:
[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;
}