Search code examples
c++vb.netenumsmarshalling

Marshal byte to enum


So i'm parsing an unmanaged structure to a managed structure with the use of the Marshal class. So far everything works as expected except for the fact that i'm struggling how to convert a unmanaged Char to a Managed enum type.

For example:

<StructLayout(LayoutKind.Sequential, Pack:=1)>
Public Structure UnamangedToManaged
     <MarshalAs(UnmanagedType.I1)>
     Public _Enum As ManagedCustomEnum
end structure


Public Enum ManagedCustomEnum
    Value_1
    Value_2
    Value_3
    Value_4
    Value_etc
End Enum

This gives the error: Unvalid combination

If i just simply remove the <MarshalAs(UnmanagedType.I1)> then the parsing works except the index for the rest of the structure is off, giving unvalid values.

Tried a lot of possibilities and also read all the MSDN articles, however still no luck.

Hopefully someone could simply point me in the right direction.


Solution

  • An Enum has a default underlying type of Int32. You have to change that to Byte in your declaration:

    Public Enum ManagedCustomEnum As Byte
        Value_1
        Value_2
        Value_3
        Value_4
        Value_etc
    End Enum