网站换服务器,什么网站专做衣服,聚名网域名综合查询,高平市规建设局网站unity项目中#xff0c;涉及到与C的相互通信#xff0c;而通信接口为C封好的动态库。所以#xff0c;传输信息时#xff0c;需要向C端发送字节流信息。 对此#xff0c;需将结构体数据转为字节流#xff0c;其代码如下#xff1a;
public static byte[] StructToBytes(…unity项目中涉及到与C的相互通信而通信接口为C封好的动态库。所以传输信息时需要向C端发送字节流信息。 对此需将结构体数据转为字节流其代码如下
public static byte[] StructToBytes(System.Object obj)
{if(obj ! null){int size Marshal.SizeOf(obj);byte[] bytes new byte[size];try{IntPtr ptr Marshal.AllocCoTaskMem(size);Marshal.StructureToPtr(obj,ptr,size);Marshal.Copy(ptr,bytes,0,size);Marshal.FreeHGlobal(ptr);}catch(Exception ex){}return bytes;}return null;
}对于接受到的字节流数据需要将其转为对应的结构体方便使用代码如下
public static System.Object BytesToStruct(byte[] bytes, Type structType)
{int size Marshal.SizeOf(structType);IntPtr buffer Marshal.AllocHGlobal(size);try{Marshal.Copy(bytes,0,buffer,size);return Marshal.PtrToStructure(buffer,structType);}finally{Marshal.FreeHGlobal(buffer);}
}