public static class StructCopyer
{
//相當於序列化與還原序列化,但是不用藉助外部檔案
//1、struct轉換為Byte[]
public static Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
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);
}
}
//2、Byte[]轉換為struct
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);
}
}
}
用法:
//InterfaceStruct為一結構體
InterfaceStruct pInterface = new InterfaceStruct();
pInterface = (InterfaceStruct)BytesToStruct(bytPipeInfo, pInterface.GetType());
轉自:http://www.cnblogs.com/jingmoxukong/articles/2118105.html