pk3DS/pk3DS.Core/StructConverter.cs
Kurt 6b74460501 Rewrite item class to struct
expand some enums out, actual numbers return actual numbers for the
HealValue so casting directly to byte preserves the value
2017-10-31 21:49:46 -07:00

28 lines
827 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
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T obj = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return obj;
}
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;
}
}
}