Using .NET 4.0 I can quickly convert a struct to and from an array of bytes by making use of the Marshal class. For example, the following simple example will run at around 1 million times per second on my machine which is fast enough for my purposes…
[StructLayout(LayoutKind.Sequential)]
public struct ExampleStruct
{
int i1;
int i2;
}
public byte[] StructToBytes()
{
ExampleStruct inst = new ExampleStruct();
int len = Marshal.SizeOf(inst);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(inst, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
But the Marshal class is not available under WinRT, which is reasonable enough for security reasons, but it means I need another way to achieve my struct to/from byte array.
I am looking for an approach that works for any fixed size struct. I could solve the problem by writing custom code for each struct that knows how to convert that particular struct to and form a byte array but that is rather tedious and I cannot help but feel there is some generic solution.
One approach would be a combination of Expressions and Reflection (I’ll leave caching as an implementation detail):
Used like so:
To read this back, it is a bit more involved: