Skip to content

Instantly share code, notes, and snippets.

@13xforever
Created May 30, 2012 12:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 13xforever/2835844 to your computer and use it in GitHub Desktop.
Save 13xforever/2835844 to your computer and use it in GitHub Desktop.
Casting array of bytes to struct and vice versa in C#
public static class CastingHelper
{
public static T CastToStruct<T>(this byte[] data) where T : struct
{
var pData = GCHandle.Alloc(data, GCHandleType.Pinned);
var result = (T)Marshal.PtrToStructure(pData.AddrOfPinnedObject(), typeof(T));
pData.Free();
return result;
}
public static byte[] CastToArray<T>(this T data) where T : struct
{
var result = new byte[Marshal.SizeOf(typeof(T))];
var pResult = GCHandle.Alloc(result, GCHandleType.Pinned);
Marshal.StructureToPtr(data, pResult.AddrOfPinnedObject(), true);
pResult.Free();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment