注:本文的内容是摘自http://blog.csdn.net/huxiangyang4/article/details/5853247的部分内容,感谢这篇博客的博主的热心分享。
class Converter
{
//Structure转为Byte数组,实现了序列化
public static Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
Console.WriteLine(size);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, buffer, false);
Byte[] bytes = new Byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
//Byte数组转为Structure,实现了反序列化
public static Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}