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);
}
}