3
我有多個結構,都以一個頭結構開始。像這樣c#與StructLayout的聯合
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完全一樣?
你是什麼意思?「我無法從標題中獲取數據」?你有例外嗎?你得到不正確的數據?您試圖從哪個字段訪問標題,「標題」或「緩衝區」字段? – 2012-04-24 14:33:05
我把它放在緩衝區中:{0xe0 0x11 0x11 0x00 0x05 0x00} 但是當我這樣做時,recBuffer.header.start是0x00而不是0xe0。 – Calypoter 2012-04-25 06:48:38