我有一个字节数组需要编组到以下结构中:
[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.Data 的类型为 byte[]):
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);
按照代码执行此操作将毫无例外地工作,但 ACSEventHeader_t 结构的 eventClass 属性具有错误的值。将类型更改为 UInt16 会得到正确的值,但是我没有枚举。
我试图将 [MarshalAs(UnmanagedType.U2)] 添加到 eventClass 属性,但这会产生此异常:
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).
任何帮助将非常感激...