当前位置 : 主页 > 编程语言 > c语言 >

c# – 非对象字段错误导致错误对齐或重叠

来源:互联网 收集:自由互联 发布时间:2021-06-25
我正在尝试创建以下结构: [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因为我正在使用紧凑的框架.
谢谢.

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;
}

对于这种类型的结构,我从不让编组人员试图处理每个成员.结构很小,所以打破每个单独的项目,如下所示:

[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;
}
网友评论