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

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

问题描述

我想创建以下结构:

    [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?

注:我不能使用包,因为我正在使用紧凑的框架。 谢谢你。

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天全站免登陆