Created
June 20, 2013 14:46
-
-
Save Unril/5823360 to your computer and use it in GitHub Desktop.
StructureToByteArray and ByteArrayToStructure
This file contains hidden or 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 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