星空网 > 软件开发 > ASP.net

类结构体 与 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;  }

 




原标题:类结构体 与 byte[] 转换类

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

tiktok 选品:https://www.goluckyvip.com/tag/81945.html
tiktok 佣金:https://www.goluckyvip.com/tag/81946.html
国际tiktok怎么才能用:https://www.goluckyvip.com/tag/81947.html
ios如何下载tiktok国际版:https://www.goluckyvip.com/tag/81948.html
tiktok到底属于哪个国家:https://www.goluckyvip.com/tag/81949.html
入驻Lazada:https://www.goluckyvip.com/tag/8195.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流