1
我有一個字節數組需要被編組爲以下的結構:是否有可能將UInt16編組爲一個枚舉?
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct ACSEventHeader_t
{
public UInt32 acsHandle;
public EventClasses eventClass;
public UInt16 eventType;
};
的EventClasses枚舉定義爲:
internal enum EventClasses
{
Request = 0,
Unsolicited = 1,
ConnectionConfirmation = 2,
CommandConfirmation = 5
}
我用做它看起來像這樣的代碼(eventBuf 。數據是類型字節[])的:
ACSEventHeader_t h = new ACSEventHeader_t();
IntPtr pt1 = Marshal.AllocHGlobal(eventBuf.Data.Length);
Marshal.Copy(eventBuf.Data, 0, pt1, eventBuf.Data.Length);
h = (ACSEventHeader_t)Marshal.PtrToStructure(pt1, typeof(ACSEventHeader_t));
Marshal.FreeHGlobal(pt1);
這樣做作爲所述代碼表示沒有異常將工作,但ACSEventH的事件類屬性eader_t結構有錯誤的值。 將類型更改爲UInt16會得到正確的值,但我沒有枚舉。
我試圖[的MarshalAs(UnmanagedType.U2)添加到事件類屬性,但是產生這種異常:
Cannot marshal field 'eventClass' of type 'ACSEventHeader_t':
enter code here`Invalid managed/unmanaged type combination (Int32/UInt32 must be
paired with I4, U4, or Error).
任何幫助,將不勝感激......
真的有幫助。我正在尋找類似於[StructLayout]的東西,但這(現在)顯然是要走的路。 – 2015-11-17 01:11:22