I have a byte array which needs to be marshalled into the following struct:
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct ACSEventHeader_t
{
public UInt32 acsHandle;
public EventClasses eventClass;
public UInt16 eventType;
};
The EventClasses enum is defined as:
internal enum EventClasses
{
Request = 0,
Unsolicited = 1,
ConnectionConfirmation = 2,
CommandConfirmation = 5
}
The code I use to do it looks like this (eventBuf.Data is of type 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);
Doing this as the code stands will work without an exception, but the eventClass property of the ACSEventHeader_t struct has the wrong value.
Changing the type to UInt16 gets the correct value, but then I don’t have an enum.
I have tried to add [MarshalAs(UnmanagedType.U2)] to the eventClass property, but that produces this exception:
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).
Any help would be much appreciated…
Just change how you declare your
enum:By default
enums are of typeInt32but you can explicitly set their type to what you need.