mirror of
https://github.com/kwsch/PKHeX
synced 2024-12-23 02:43:13 +00:00
429a3b1a08
Closes #2785 , not making a GUI for this (someone else can do it) Moves RTC3 to the appropriate folder
46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using System;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace PKHeX.Core
|
|
{
|
|
internal 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 T ToClass<T>(this byte[] bytes) where T : class
|
|
{
|
|
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
|
try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); }
|
|
finally { handle.Free(); }
|
|
}
|
|
|
|
public static byte[] ToBytesClass<T>(this T obj) where T : class
|
|
{
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|