3

I have multiple structs that all starts with a header struct. Like this

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

The header is

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

The problem now is that I need to union them with a Byte[]. I tried it with this

[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 can't get the data from the header. How can I make c# do the same as I can do with union in c++?

Calypoter
  • 155
  • 2
  • 11
  • What do you mean by "I can't get the data from the header"? Do you get an exception? Do you get incorrect data? From which field are you trying to access the header, the `header` or `buffer` field? – Allon Guralnek Apr 24 '12 at 14:33
  • I put this in buffer: { 0xe0 0x11 0x11 0x00 0x05 0x00 } But when I did this recBuffer.header.start is was 0x00 instead of 0xe0. – Calypoter Apr 25 '12 at 06:48

1 Answers1

8

Byte[] is a reference type field, which you cannot overlay with 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];
};
Botz3000
  • 39,020
  • 8
  • 103
  • 127