Union in C # using StructLayout

I have several structures that start with a header structure. Like this

public struct BaseProtocol {
    public Header header;
    public Footer footer;
};

Headline

public struct Header {
    public Byte start;
    public Byte group;
    public Byte dest;
    public Byte source;
    public Byte code;
    public Byte status;
};

Now the problem is that I need to combine them with byte []. I tried this with

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

When I fill the buffer with data, I cannot get the data from the header. How can I make C # do the same thing that I can do with union in C ++?

+3
source share
1 answer

Byte [] is a reference type field that cannot be superimposed on a value type field. You need a fixed size buffer, and you need to compile it with /unsafe. Like this:

[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];
};
+7
source

All Articles