Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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