我有一个字节数组需要编组到以下结构中:
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct ACSEventHeader_t
{
public UInt32 acsHandle;
public EventClasses eventClass;
public UInt16 eventType;
};
Run Code Online (Sandbox Code Playgroud)
EventClasses枚举定义为:
internal enum EventClasses
{
Request = 0,
Unsolicited = 1,
ConnectionConfirmation = 2,
CommandConfirmation = 5
}
Run Code Online (Sandbox Code Playgroud)
我用它做的代码看起来像这样(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);
Run Code Online (Sandbox Code Playgroud)
在代码中执行此操作将无异常地工作,但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).
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激...
只需更改您声明的方式enum:
internal enum EventClasses : short
{
Request = 0,
Unsolicited = 1,
ConnectionConfirmation = 2,
CommandConfirmation = 5
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,enums是类型,Int32但您可以明确地将其类型设置为您需要的类型.