Last Update: 2015/12/1 22:15+08
Intro
C# use Marshal to convertion between byte array and struct
Content
public static byte[] ToBytes(T obj)
{
Byte[] bytes = new Byte[Marshal.SizeOf(typeof(T))];
GCHandle pinStructure = GCHandle.Alloc(obj, GCHandleType.Pinned);
try
{
Marshal.Copy(pinStructure.AddrOfPinnedObject(), bytes, 0, bytes.Length);
return bytes;
}
finally
{
pinStructure.Free();
}
}
public static T FromBytes(byte[] buffer)
{
int size = Marshal.SizeOf(typeof(T));
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(buffer, 0, ptr, size);
T data = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return data;
}
沒有留言:
張貼留言