You can use unsafe
to access any blittable (arrays, strings, structs etc.) types as a byte pointer.
Local variables of value types don't have to be pinned:
public unsafe void ReadAsBytePointer(MyStruct obj)
{
byte* ptr = (byte*)&obj;
...
}
Arrays must be pinned. The easiest solution is to use fixed:
public unsafe void ReadAsBytePointer(MyStruct[] input)
{
fixed(MyStruct* ptr = input)
{
byte* byteArray = (byte*)ptr;
}
}
For a general case without adding unsafe
to your code you can use GCHandle:
static byte[] GetBytes<T>(T input)
where T : struct
{
int size = Marshal.SizeOf(typeof(T));
byte[] result = new byte[size];
GCHandle gc = GCHandle.Alloc(input, GCHandleType.Pinned);
try
{
Marshal.Copy(gc.AddrOfPinnedObject(), result, 0, size);
}
finally
{
gc.Free();
}
return result;
}