Reputation: 665
I'm trying to convert a byte array of size 1 to an enum:
public enum InformationMessageLevel : byte
{
Information = 0,
Warning = 1,
Error = 2,
Fatal = 3
}
Using marshalling:
// bytes = byte[1] = 0
// t is typeof(InformationMessageLevel)
unsafe
{
fixed (byte* p = bytes)
{
var localPtr = p;
return Marshal.PtrToStructure((IntPtr)localPtr, t);
}
}
But I get the error:
"The specified structure must be blittable or have layout information.\r\nParameter name: structure"
The reason I'm using marshaling with an IntPtr, is this method is used to unserialize data dynamically to properties of different types.
Upvotes: 0
Views: 453
Reputation: 15197
A dynamic solution without using marshaling:
byte[] bytes = { 0 };
var t = typeof(InformationMessageLevel);
var result = Enum.ToObject(t, bytes[0]);
Console.WriteLine(result);
Output:
Information
Upvotes: 2