Class struct and byte [] conversion class, byte Conversion
public static class StructConvert { public static object BytesToStruct(byte[] bytes, Type strcutType) { int size = Marshal.SizeOf(strcutType); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(bytes, 0, buffer, size); return Marshal.PtrToStructure(buffer, strcutType); } finally { Marshal.FreeHGlobal(buffer); } } public static byte[] StructToBytes(object structObj) { int size = Marshal.SizeOf(structObj); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structObj, buffer, false); byte[] bytes = new byte[size]; Marshal.Copy(buffer, bytes, 0, size); return bytes; } finally { Marshal.FreeHGlobal(buffer); } } }
Class struct example. Both struct and class can be converted according to project requirements.
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct MapRecord { public int Id; public int Rebirth; public int CoorX; public int CoorY; public int CoorZ; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 204)] public byte[] Unknown1; public int Dir; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] Unknown2; public int MiniMap; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public byte[] Unknown3; }