简体   繁体   中英

Alignment error recreating C++ union type with non-primitive types in C#

I have a simple union (byte array and a short) in C++ which I am attempting to port to C# and getting 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. I suspect that my implementation doesn't work because I have array as one of the struct members.

existing C++ union:

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

attempted C# implementation:

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

similar question was answered before but it seems to work only for primitive types: C++ union in C#

Thank you in advance.

Have you tried "StructLayout(LayoutKind.Explicit, Size =2, Pack=1)"? Seems to be a problem with C# default to a 4-byte packing size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM