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); } } }
類結構體示例,struct和class 均可轉換,根據項目需要
[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; }