mirror of
https://github.com/kwsch/pk3DS.git
synced 2026-03-21 17:34:37 -05:00
26 lines
739 B
C#
26 lines
739 B
C#
using System;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace pk3DS.Core;
|
|
|
|
public static class StructConverter
|
|
{
|
|
public static T ToStructure<T>(this byte[] bytes) where T : struct
|
|
{
|
|
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
|
try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); }
|
|
finally { handle.Free(); }
|
|
}
|
|
|
|
public static byte[] ToBytes<T>(this T obj) where T : struct
|
|
{
|
|
int size = Marshal.SizeOf(obj);
|
|
byte[] arr = new byte[size];
|
|
|
|
IntPtr ptr = Marshal.AllocHGlobal(size);
|
|
Marshal.StructureToPtr(obj, ptr, true);
|
|
Marshal.Copy(ptr, arr, 0, size);
|
|
Marshal.FreeHGlobal(ptr);
|
|
return arr;
|
|
}
|
|
} |