使用StructLayout在c#中联合

Cal*_*ter 3 c# union structlayout

我有多个结构,都以头结构开头.像这样

public struct BaseProtocol {
    public Header header;
    public Footer footer;
};
Run Code Online (Sandbox Code Playgroud)

标题是

public struct Header {
    public Byte start;
    public Byte group;
    public Byte dest;
    public Byte source;
    public Byte code;
    public Byte status;
};
Run Code Online (Sandbox Code Playgroud)

现在的问题是我需要将它们与Byte []结合起来.我试过这个

[StructLayout( LayoutKind.Explicit, Size=255 )]
public struct RecBuffer {

    [FieldOffset( 0 )]
    public Header header;

    [FieldOffset( 0 )]
    [MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 255 )]
    public Byte[] buffer;
};
Run Code Online (Sandbox Code Playgroud)

当我用缓冲区填充数据时,我无法从标题中获取数据.如何使c#与c ++中的union相同?

Bot*_*000 8

字节[]是引用类型字段,您不能使用值类型字段覆盖它.你需要一个固定大小的缓冲区,你需要编译它/unsafe.像这样:

[StructLayout(LayoutKind.Explicit, Size = 255)]
public unsafe struct RecBuffer
{

    [FieldOffset(0)]
    public long header;

    [FieldOffset(0)]
    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 255)]
    public fixed Byte buffer[255];
};
Run Code Online (Sandbox Code Playgroud)