当前位置: 代码迷 >> C# >> 类结构体 与 byte[] 变换类
  详细解决方案

类结构体 与 byte[] 变换类

热度:173   发布时间:2016-04-28 08:18:00.0
类结构体 与 byte[] 转换类
    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;    }

 

  相关解决方案