Skip to content

Instantly share code, notes, and snippets.

@Wind4
Created December 11, 2013 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wind4/7906384 to your computer and use it in GitHub Desktop.
Save Wind4/7906384 to your computer and use it in GitHub Desktop.
Reading binary data structure filled.
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