Skip to content

Instantly share code, notes, and snippets.

@Unril
Created June 20, 2013 14:46
Show Gist options
  • Save Unril/5823360 to your computer and use it in GitHub Desktop.
Save Unril/5823360 to your computer and use it in GitHub Desktop.
StructureToByteArray and ByteArrayToStructure
public static byte[] StructureToByteArray<T>(T obj) {
int len = Marshal.SizeOf(typeof (T));
var arr = new byte[len];
IntPtr ptr = IntPtr.Zero;
try {
ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
}
finally {
if (ptr != IntPtr.Zero) {
Marshal.FreeHGlobal(ptr);
}
}
return arr;
}
public static T ByteArrayToStructure<T>(byte[] bytearray) {
int len = Marshal.SizeOf(typeof (T));
IntPtr ptr = IntPtr.Zero;
T obj;
try {
ptr = Marshal.AllocHGlobal(len);
Marshal.Copy(bytearray, 0, ptr, len);
obj = (T) Marshal.PtrToStructure(ptr, typeof (T));
}
finally {
if (ptr != IntPtr.Zero) {
Marshal.FreeHGlobal(ptr);
}
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment