gpt4 book ai didi

c# - 将字节数组转换为对象 C++ | C++ 中的 C# 位转换器

转载 作者:行者123 更新时间:2023-11-28 04:03:19 26 4
gpt4 key购买 nike

我有一个 C++ 服务器,它从用 C# 编写的客户端接收字节数组(我正在使用 SFML UDP 套接字)。在客户端中,我使用 System.Bitconverter 对数据包信息进行编码。

我将如何从 C++ 服务器上的数据包中提取信息,因为它是作为 string/char[] 接收的。使用 C# 中的 Bitconverter,我可以执行 Bitconverter.GetBytes (...)

我不是很擅长 C++,所以我为这个 nooby 问题道歉。任何帮助,将不胜感激!提前致谢!

客户端(为Unity游戏引擎编写):

// - Sending this Player's data: -

byte[] buff = new byte[7 * sizeof(float) + 3 * sizeof (int)];

int tag = 1;
int curSize = 0;

Buffer.BlockCopy(BitConverter.GetBytes(tag), 0, buff, curSize, sizeof (int));
curSize += sizeof(int);
Buffer.BlockCopy(BitConverter.GetBytes(id), 0, buff, curSize, sizeof(int));
curSize += sizeof(int);
Buffer.BlockCopy(BitConverter.GetBytes(GetComponent<controls>().killedID), 0, buff, curSize, sizeof(int));
curSize += sizeof(int);


Buffer.BlockCopy(BitConverter.GetBytes(transform.position.x), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);
Buffer.BlockCopy(BitConverter.GetBytes(transform.position.y), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);
Buffer.BlockCopy(BitConverter.GetBytes(transform.position.z), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);

Buffer.BlockCopy(BitConverter.GetBytes(transform.eulerAngles.x), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);
Buffer.BlockCopy(BitConverter.GetBytes(GetComponentInChildren<Camera> ().transform.eulerAngles.y), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);
Buffer.BlockCopy(BitConverter.GetBytes(transform.eulerAngles.z), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);
Buffer.BlockCopy(BitConverter.GetBytes(myGun.transform.eulerAngles.x), 0, buff, curSize, sizeof(float));
curSize += sizeof(float);


sendData(buff);

}
private void sendData(byte[] data)
{
udp.Send(data, data.Length);
}

最佳答案

假设您的 C++ 和 C# 编译器同意 intfloat 的大小和形状并且您的客户端/服务器具有匹配的字节顺序,您可以执行以下操作:

struct packet {
int tag, id, killedID;
float posX, posY, posZ;
float rotX, rotY, rotZ;
float rotGun;
};

packet read_packet(const char *in) {
packet ret;
ret.tag = *(int *)in; in += sizeof int;
ret.int = *(int *)in; in += sizeof int;
ret.posX = *(float *)in; in += sizeof float;
...
return ret;
}

但是,我建议使用 Flatbuffers反而。这使您能够拥有数据包内容的单一规范,并拥有为您生成序列化代码的工具。

关于c# - 将字节数组转换为对象 C++ | C++ 中的 C# 位转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59155386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com