简体   繁体   English

使用StructLayout在c#中联合

[英]Union in c# with StructLayout

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[]. 现在的问题是我需要将它们与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++? 如何使c#与c ++中的union相同?

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 . 您需要一个固定大小的缓冲区,您需要使用/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];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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