I found two method to convert byte[] to structure. but I don’t know if there is any difference between these two methods? can anyone know which is better (performance, …)?
#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;
}
I did a benchmark for you using the following code:
I came to the following results: