lyra-wasm-scripting-test/guests/csharp/LyraApi/Marshalling.cs

47 lines
1.2 KiB
C#
Raw Normal View History

namespace LyraApi;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
public static class Marshalling {
internal struct AlignmentHelper<T> where T : unmanaged
{
public byte Padding;
public T Target;
}
public static int AlignmentOf<T>() where T : unmanaged
{
return (int)Marshal.OffsetOf<AlignmentHelper<T>>(nameof(AlignmentHelper<T>.Target));
}
public static byte[] GetBytes<T>([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<T>(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();
}
}
}