Question

I am having a problem with sending vectors across an enet connection because vectors seem to be represented with their own sort of data possibly pointing to where the vectors internal data is actually stored, and I cannot figure out how to access it.

Both the client and the server have this data structure on them:

typedef struct {
    unsigned int type;
    vector<int> content;
} packetFormat;

The data is being sent to the server like this:

packetFormat var;
var.type = 5; //sizeof is 4 bytes
var.content = {1, 3, 5, 20, 10, 50, 10, 10}; //sizeof is 16 bytes regardless of data
//total 20 bytes, 21 counting \0 character
ENetPacket* packet = enet_packet_create((char*)&var, sizeof(var) + 1, ENET_PACKET_FLAG_RELIABLE);
enet_host_broadcast(client, 0, packet);

The server then receives and casts the data to the same structure like this:

//receives 21 bytes, which is correct
packetFormat* var = (packetFormat*)(event.packet->data);

Checking the variables however, var->type is equal to 5, which is correct but when I try to check the size() or any contents of the vector, it either crashes the server or gives garbage data. As I said before I think this is because the vector thing in the struct is actually a pointer, but does anyone know how to transmit and re-assemble the raw data? Thanks.

No correct solution

OTHER TIPS

If understand what you code is doing, it's simply serialising the struct as though it had no indirections, like fixed width datum.

The vector internally has a pointer to it's data, so serialising the vector in the struct you are only sending the value of the pointer, not the actual data itself pointed to by it.

Also there would be very little to absolutely no guarentee that the sizeof and layout of the vector would be the same at the host and the client size.

If you want to send the vector I would consider using a C++ network library that understands vectors, like Boost.Asio for example.

insert all the elements of vector in a char* variable of a class. this will create a stream of bytes in memory. at the receiving end, take care of the byte offset from which the vector has to be started to be copied back.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top