我找到了两种转换byte[]
为结构的方法。但我不知道这两种方法有什么区别吗?谁能知道哪个更好(性能,...)?
#1:
public static T ByteArrayToStructure<T>(byte[] buffer)
{
int length = buffer.Length;
IntPtr i = Marshal.AllocHGlobal(length);
Marshal.Copy(buffer, 0, i, length);
T result = (T)Marshal.PtrToStructure(i, typeof(T));
Marshal.FreeHGlobal(i);
return result;
}
#2:
public static T ByteArrayToStructure<T>(byte[] buffer)
{
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return result;
}