日期:2014-05-17 浏览次数:20990 次
//结构体代码
public struct DateSkillList
{
public byte datatypes;
public int player_id;
public ArrayList skill_list;
}
//skill_list包含的是一个Skillslistdate的结构体;
public struct Skillslistdate
{
public int skill_id;
public int skill_level;
}
//处理部分
public class bytes
{
public gobyte()
{
DateSkillList msg=new DateSkillList();
Skillslistdate smg=new Skillslistdate();
smg.skill_id=10001;
smg.skill_level=1;
msg.skill_list.add(smg);
byte[] buffer=Tool.StructToBytes(msg);
}
}
//Tool 部分
public class Tool
{
public static byte[] StructToBytes(object obj)
{
int size = Marshal.SizeOf(obj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size); //分配结构体大小的内存空间
Marshal.StructureToPtr(obj, structPtr, false); //将结构体拷到分配好的内存空间
Marshal.Copy(structPtr, bytes, 0, size); //从内存空间拷到byte数组
Marshal.FreeHGlobal(structPtr); //释放内存空间
return bytes;
}
//网络发送部分
NetWorks.AsyncSendMessage(buffers, clns);
public static byte[] StructToBytes(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
bf.Serialize(stream, obj);
return stream.ToArray();
}
}