字节数组反序列化成对象:
using System.Runtime.InteropServices;
byte[] buffer;
Type curType = typeof(T);
int num1 = Marshal.SizeOf(curType);
int num2 = buffer.Length;
if(num1 != num2)
Array.Resize(ref buffer, num1);
IntPtr ptr = Marshal.AllocHGlobal(num1);
Marshal.Copy(buffer, 0, intPtr, num1);
object obj = Marshal.PtrToStructure(ptr, curType);
Marshal.FreeHGlobal(ptr);
return (T)obj;
对象序列化成字节数组:
using System.Runtime.InteropServices;
int length = Marshal.SizeOf(obj);
byte[] array = new byte[length];
IntPtr ptr = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arrar, 0, length);
Marshal.FreeHGlobal(ptr);
return array;