3

我有多个结构都以标头结构开头。像这样

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 一样?

4

1 回答 1

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];
};
于 2012-04-24T14:39:36.580 回答