Reputation: 81
I have a C++ server that receives a byte array from a client written in C# (I'm using SFML UDP sockets). In the client, I encode the packet information using System.Bitconverter
.
How would I go about extracting the information from the packet on the C++ server given that it is received as a string/char[]
. With Bitconverter in C#, I could just do Bitconverter.GetBytes (...)
.
I'm not great in C++ so I apologise for the nooby question. Any help would be appreciated! Thanks in advance!
The client (written for the Unity game engine):
// - 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);
}
Upvotes: 0
Views: 960
Reputation: 43
Here is a C++ header-only library that may be of help. It is a port of C# BitConverter
class for C++.
Upvotes: 0
Reputation: 31020
Assuming your C++ and C# compilers agree about the size and shape of int
and float
and your client/server have matching endianness, you can do the following:
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;
}
However, I would advise using Flatbuffers instead. This enables you to have a single specification of the packet contents and has tooling to generate the serialization code for you.
Upvotes: 1