serialize complex C++ structures between client and server

Viewed 536

I am writing C++ ZeroMQ Client and server programs for the same platform. I need to trigger some functions with arguments on the server. The arguments are complex structures. I have just started to try this out. I am trying to fill a structure and fill it to a char* buffer to see if the bytes are filled out in sequence as per the structure.

But when i try to print the buffer, it prints garbage. Please advice what might be wrong. And is this the elegant way to do this? I cannot use gRPC or Protobuffs as the message contains complex structures.

    struct employee {
    uint8_t byt;
    int arr[10] = {0};
    int number;
    uint32_t acct;
};

int main ()
{
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_PAIR);
    struct employee *e = new employee;
    e->byt = 0xff;
    e->arr[0] = 15;
    e->number = 25555;
    e->acct = 45;

    std::cout << "Connecting to hello world server…" << std::endl;
    socket.connect ("tcp://localhost:5555");

    char *temp = (char*)malloc(sizeof(employee));
    memcpy(temp,e,sizeof(employee));

    zmq::message_t request(sizeof(employee));
    char *temp1 = temp;
    for (int i = 0;i<sizeof(employee);i++) {
        std::cout<<temp1[i]<<std::endl;
    }
    memcpy ((void *)request.data(),(void*)temp, sizeof(employee));
    socket.send (request);

    //  Get the reply.
    zmq::message_t reply;
    socket.recv (&reply);
    return 0;
}
1 Answers

Two points I would like to share here.

  1. the buffer (temp) contains binary representation of your data structure. If you want to check if the content is meaningful, you can cast the pointer type back to its original pointer.ie:

struct employee * employeePtr = static_cast< struct employee *>(temp);

cout << employeePtr ->number;

...

  1. The way you de-serialize is okay when the object you are trying to serialize occupies continuous memory. When it is not the case, you will have to handle them some other way (using stream for example). Examples of such cases include:

    • when you have pointer, shared_ptr etc. to some allocated memory

    • container classes

Related