I have a need to turn various structures into byte arrays to be sent over serial port to another machine. I created generic extensions to turn any structure into a byte array and from a byte array back into a given structure.
I've not used the Marshal
class often, and I'm uncomfortable manipulating memory on this level.
- Do I need to explicitly free any memory?
- Is this an efficient implementation? I'll be calling this a lot, it's important that it's efficient in both terms of memory and speed.
public static class StructureExtensions
{
public static byte[] ToByteArray<T>(this T structure) where T : struct
{
var bufferSize = Marshal.SizeOf(structure);
var byteArray = new byte[bufferSize];
IntPtr handle = Marshal.AllocHGlobal(bufferSize);
Marshal.StructureToPtr(structure, handle, true);
Marshal.Copy(handle, byteArray, 0, bufferSize);
return byteArray;
}
public static T ToStructure<T>(this byte[] byteArray) where T : struct
{
var packet = new T();
var bufferSize = Marshal.SizeOf(packet);
IntPtr handle = Marshal.AllocHGlobal(bufferSize);
Marshal.Copy(byteArray, 0, handle, bufferSize);
return Marshal.PtrToStructure<T>(handle);
}
}
Example Call:
var point = new Point(10,5); byte[] serialized = point.ToByteArray(); Point deserialized = serialized.ToStructure<Point>();
where T : struct clause
- unless you want to impose it for some other reason. Maybe I am reading it wrong \$\endgroup\$