Created
May 30, 2012 12:06
-
-
Save 13xforever/2835844 to your computer and use it in GitHub Desktop.
Casting array of bytes to struct and vice versa in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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