Created
December 11, 2013 07:35
-
-
Save Wind4/7906384 to your computer and use it in GitHub Desktop.
Reading binary data structure filled.
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
using System; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
namespace Common | |
{ | |
/// <summary> | |
/// 一种通用的将byte数组流转换为对象的方法 | |
/// </summary> | |
/// <see cref="http://www.cnblogs.com/TianFang/archive/2012/10/06/2712987.html"/> | |
static class MarshalExtend | |
{ | |
public static byte[] ObjectToBytes<T>(T obj) | |
{ | |
var size = Marshal.SizeOf(typeof(T)); | |
var data = new byte[size]; | |
IntPtr ptr = Marshal.AllocHGlobal(size); | |
try | |
{ | |
Marshal.StructureToPtr(obj, ptr, true); | |
// Copy the array to unmanaged memory. | |
Marshal.Copy(ptr, data, 0, size); | |
return data; | |
} | |
finally | |
{ | |
// Free the unmanaged memory. | |
Marshal.FreeHGlobal(ptr); | |
} | |
} | |
public static T BytesToObject<T>(byte[] data) | |
{ | |
var size = Marshal.SizeOf(typeof(T)); | |
IntPtr ptr = Marshal.AllocHGlobal(size); | |
try | |
{ | |
// Copy the array to unmanaged memory. | |
Marshal.Copy(data, 0, ptr, size); | |
return (T)Marshal.PtrToStructure(ptr, typeof(T)); | |
} | |
finally | |
{ | |
// Free the unmanaged memory. | |
Marshal.FreeHGlobal(ptr); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment