- 最后登录
- 2016-10-1
- 注册时间
- 2013-12-28
- 阅读权限
- 90
- 积分
- 5805
- 纳金币
- 2954
- 精华
- 3
|
首先本地要与服务器发送的数据的组织结构一样
csharpcode:- /// <summary>
- /// 装备基础信息
- /// </summary>
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- public struct Equipstruct
- {
- public int EquipID;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
- public byte[] EquipName;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
- public byte[] EquipIntroduce;
- public int EquipEvolveMaxLevel; //强化次数上限
-
- public int EquipReformMaxLevel;//改造次数上限
- public int EquipType;//装备类型
- public int EquipQuality; //品质
- public int EquipPower; //破坏力
- public int EquipShotSpeed; //射速
- public int EquipEnergyDown; //能耗
-
- public int EquipHitRateValue; //命中率
- public int EquipMaxSpeed; //最快速度
-
- public int EquipAcceleration; //加速度
-
- public int EquipHideValue; //自动规避值
-
- public int EquipHoldValue; //姿态维持值
- public int EquipDefense; //防御
-
- public int EquipRecover; //回复
-
- public int EquipRangeValue; //拾取范围
-
- public int EquipRecoverRate; //通行
- public int EquipSuitID; //套装ID
- public int EquipDurabilityMaxValue; //耐久度上限
- public int EquipPrice; //售价
-
- public int EquipSellPrice; //卖出价
- }
复制代码
将byte数组解析成对应的结构体
csharpcode:- using UnityEngine;
- using System.Collections;
- using System.Runtime.InteropServices;
- using System;
- public class BasicDateMagner {
-
-
- /// <summary>
- /// 结构体转化成字节数组
- /// </summary>
- /// <returns>字节数组</returns>
- /// <param name="obj">结构体对象</param>
- static public byte[] StructToBytes(object obj)
- {
- int size = Marshal.SizeOf (obj);
-
- byte[] bytes = new byte[size];
-
- //分配结构体大小的内存空间
- IntPtr structPtr = Marshal.AllocHGlobal (size);
-
- //将结构体拷到分配好的内存空间
- Marshal.StructureToPtr (obj,structPtr,false);
-
- //从内存空间拷到byte数组
- Marshal.Copy (structPtr,bytes,0,size);
-
- //释放内存空间
- Marshal.FreeHGlobal(structPtr);
-
- return bytes;
- }
-
-
- /// <summary>
- /// 字节数组转化成结构体
- /// </summary>
- /// <returns>结构体</returns>
- /// <param name="bytes">字节数组</param>
- /// <param name="type">结构体类型</param>
- static public object BytesToStruct(byte[] bytes, Type type)
- {
- //得到结构的大小
- int size = Marshal.SizeOf (type);
- if(size > bytes.Length)
- {
- return null;
- }
-
- //分配结构大小的内存空间
- IntPtr structPtr = Marshal.AllocHGlobal(size);
- //将byte数组拷到分配好的内存空间
- Marshal.Copy(bytes,0,structPtr,size);
- //将内存空间转换为目标结构
- object obj = Marshal.PtrToStructure (structPtr,type);
- //将内存空间转换为目标结构
- Marshal.FreeHGlobal (structPtr);
-
- return obj;
- }
-
- }
复制代码 |
|