我有多个结构都以头结构开头。喜欢这个
public struct BaseProtocol {
public Header header;
public Footer footer;
};
标题是
public struct Header {
public Byte start;
public Byte group;
public Byte dest;
public Byte source;
public Byte code;
public Byte status;
};
现在的问题是我需要将它们与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;
};
当我用缓冲区填充数据时,我无法从标题中获取数据。我如何使c#与c ++中的union相同?
答案 0 :(得分:8)
Byte []是一个引用类型字段,您无法使用值类型字段覆盖它。您需要一个固定大小的缓冲区,您需要使用/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];
};