【问题标题】:Alignment error recreating C++ union type with non-primitive types in C#在 C# 中使用非原始类型重新创建 C++ 联合类型时出现对齐错误
【发布时间】:2018-06-22 17:41:59
【问题描述】:

我在 C++ 中有一个简单的联合(字节数组和一个短),我试图将其移植到 C# 并获得 Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field. 我怀疑我的实现不起作用,因为我将数组作为结构成员之一。

现有的 C++ 联合:

union {
    char    c[2];
    short        data;
} u;

尝试的 C# 实现:

[StructLayout(LayoutKind.Explicit, Size =2)]
public struct Union
{
    [MarshalAs(UnmanagedType.LPArray)]
    [FieldOffset(0)]
    public byte[] c;
    [FieldOffset(0)]
    public short data;
}

之前回答过类似的问题,但它似乎只适用于原始类型:C++ union in C#

提前谢谢你。

【问题讨论】:

    标签: c# c++ struct marshalling unions


    【解决方案1】:

    您是否尝试过“StructLayout(LayoutKind.Explicit, Size =2, Pack=1)”?似乎是 C# 默认为 4 字节打包大小的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多