2024-11-08 00:28:35 +00:00
|
|
|
namespace LyraApi;
|
|
|
|
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
using System.Runtime.InteropServices;
|
|
|
|
|
2024-11-09 02:05:02 +00:00
|
|
|
public static class MarshalUtils
|
|
|
|
{
|
2024-11-08 00:28:35 +00:00
|
|
|
internal struct AlignmentHelper<T> where T : unmanaged
|
|
|
|
{
|
2024-11-09 02:05:02 +00:00
|
|
|
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value 0
|
2024-11-08 00:28:35 +00:00
|
|
|
public byte Padding;
|
|
|
|
public T Target;
|
2024-11-09 02:05:02 +00:00
|
|
|
#pragma warning restore CS0649 // Field is never assigned to, and will always have its default value 0
|
2024-11-08 00:28:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static int AlignmentOf<T>() where T : unmanaged
|
|
|
|
{
|
|
|
|
return (int)Marshal.OffsetOf<AlignmentHelper<T>>(nameof(AlignmentHelper<T>.Target));
|
|
|
|
}
|
|
|
|
|
2024-11-09 02:05:02 +00:00
|
|
|
public static byte[] GetBytes<T>([DisallowNull] T data)
|
|
|
|
{
|
2024-11-08 00:28:35 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2024-11-09 02:05:02 +00:00
|
|
|
public static T? FromBytes<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data)
|
2024-11-08 00:28:35 +00:00
|
|
|
{
|
|
|
|
var ptr = GCHandle.Alloc(data, GCHandleType.Pinned);
|
2024-11-09 02:05:02 +00:00
|
|
|
try
|
|
|
|
{
|
|
|
|
//var res = (T?)Marshal.PtrToStructure(ptr.AddrOfPinnedObject(), typeof(T));
|
|
|
|
var res = Marshal.PtrToStructure<T>(ptr.AddrOfPinnedObject());
|
2024-11-08 00:28:35 +00:00
|
|
|
return res;
|
2024-11-09 02:05:02 +00:00
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
2024-11-08 00:28:35 +00:00
|
|
|
ptr.Free();
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|