/// <summary> /// Converts a byte array to a structure instance. /// </summary> /// <param name="buffer">The byte array to unmarshal.</param> /// <typeparam name="T">The structure type.</typeparam> /// <returns>A new structure of type <typeparamref name="T" />.</returns> public static T BufferToStructure <T>(byte[] buffer) where T : struct { Debug.Assert(buffer.Length == Marshal.SizeOf <T>(), "buffer.Length == Marshal.SizeOf<T>()"); using var handle = new DisposableGcHandle(buffer, GCHandleType.Pinned); return(Marshal.PtrToStructure <T>(handle.AddrOfPinnedObject())); }
/// <summary> /// Marshals a structure to a byte array. /// </summary> /// <param name="data">The structure to marshal.</param> /// <typeparam name="T">The structure type.</typeparam> /// <returns>An array of bytes representing the structure.</returns> public static byte[] MarshalStruct <T>(T data) where T : struct { var size = Marshal.SizeOf <T>(); var buffer = new byte[size]; using var gcHandle = new DisposableGcHandle(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(data, gcHandle.AddrOfPinnedObject(), false); return(buffer); }