namespace LyraApi; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; public static class Marshalling { internal struct AlignmentHelper where T : unmanaged { public byte Padding; public T Target; } public static int AlignmentOf() where T : unmanaged { return (int)Marshal.OffsetOf>(nameof(AlignmentHelper.Target)); } public static byte[] GetBytes([DisallowNull] T data) { int size = Marshal.SizeOf(data); byte[] arr = new byte[size]; IntPtr ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(data, ptr, true); Marshal.Copy(ptr, arr, 0, size); } finally { Marshal.FreeHGlobal(ptr); } return arr; } public static T? FromBytes(byte[] data) where T : struct { var ptr = GCHandle.Alloc(data, GCHandleType.Pinned); try { var res = (T?) Marshal.PtrToStructure(ptr.AddrOfPinnedObject(), typeof(T)); return res; } finally { ptr.Free(); } } }