I'm looking for the most straightforward way to convert a byte[] to a struct. My testing indicates that this works:
[StructLayout(LayoutKind.Explicit, Size = OrderStruct.SIZE)]
public unsafe struct OrderStruct
{
public const int SIZE = 16;
[FieldOffset(0)]
private fixed byte _data[OrderStruct.SIZE];
[FieldOffset(0), MarshalAs(UnmanagedType.I4)]
public int AssetId;
[FieldOffset(4), MarshalAs(UnmanagedType.I4)]
public int OrderQty;
[FieldOffset(8), MarshalAs(UnmanagedType.R8)]
public double Price;
public static OrderStruct FromBytes(ref byte[] data)
{
if (data.Length < SIZE)
throw new ArgumentException("Size is incorrect");
OrderStruct t = default(OrderStruct);
fixed (byte* src = data)
{
Buffer.MemoryCopy(src, t._data, SIZE, SIZE);
}
return t;
}
public byte[] ToBytes()
{
var result = new byte[SIZE];
fixed (byte* dst = result)
fixed (byte* src = this._data)
{
Buffer.MemoryCopy(src, dst, result.Length, SIZE);
}
return result;
}
}
Am I missing an edge case or is this an ok way to solve this problem?
Additional info:
- Performance is important otherwise I would just convert each item individually with BitConverter and this solution is observably faster.
- I don't really need a generic solution as I'm only going to be doing this for 1 or 2 items in my code base.
- In my case I don't need to worry about endianness as that is already handled elsewhere.