非对象字段错误对齐或重叠 [英] Incorrectly aligned or overlapped by a non-object field error

查看:33
本文介绍了非对象字段错误对齐或重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建以下结构:

I'm trying to create the following structure:

    [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 处的对象字段,该字段未正确对齐或与非对象字段重叠.

Could not load type 'Message' from assembly because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.

有人知道为什么会导致错误吗?

Does anyone know why this is causing an error?

注意:我不能使用 Pack,因为我使用的是紧凑型框架.谢谢.

Note: I can not use Pack because I'm working with the compact framework. Thanks.

推荐答案

CF 封送拆收器不太擅长这种类型的事情,并且您正在尝试的内容不受支持.问题是它知道第一个元素是未对齐的,但它似乎不明白数组中的每个元素也会未对齐.

The CF Marshaler isn't so good at this type of thing and what you're attempting is unsupported. The problem is that it knows that the first element is unaligned, but it seems to not understand that each element in the array would also be unaligned.

您可以在此示例中看到该行为有效:

You can see the behavior works in this example:

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

对于这种类型的结构,我从不让封送拆收器尝试处理每个成员.结构很小,所以像这样分解每个单独的项目:

For this type of structure, I never let the marshaler try to handle each of the members anyway. The structure is small, so break out each individual item like this:

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

或者像这样使用模拟的联合":

or use a simulated "union" like this:

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

这篇关于非对象字段错误对齐或重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆