0

how to do serialization and deserialization of the structures sent from the c++ socket to qt udp socket

Actually iam trying out this logic for serialization and deserailization like this

struct stCardInfo
{
    unsigned short nsCardType;
    unsigned short nsNoOfSignals;
    unsigned short nsStatus;
};

struct stErrorInfo
{
    unsigned short nsErrorType;
    char ErrorInfo[8];
};
struct stInitHealthCheck
{
    unsigned short nsNoOfCards;
    stCardInfo* lsCardInfo;
};

   stInitHealthCheck stHealthCheck;

   unsigned short *q = (unsigned short *)data;

   stHealthCheck.nsNoOfCards = *q;       q++;

   stHealthCheck.lsCardInfo = new stCardInfo;
   stHealthCheck.lsCardInfo->nsCardType = *q;   q++;
   stHealthCheck.lsCardInfo->nsNoOfSignals = *q;     q++;
   stHealthCheck.lsCardInfo->nsStatus= *q;     q++;

But if the structure is more then my decoding everytime to particular datatype will become complex and time consuming so iam asking is there any efficient way of doing the serialization and deserialization so that my decoding and encoding the udp packet sent and received can be done very fast

1 Answers1

1

The endianness might be different on the communicating devices, you should use htons or ntohs when sending/receiving unsigned shorts.

Also, if you are casting the struct to a char* buffer on the sending side, please note that this is not a cross-platform way for writing a communication protocol. The struct might have a different representation at the binary-level when your code is compiled using a different compiler.

But why mess up with all this low-level stuff when you have many serialization libraries that are already available. Just pick up one from the list!

If both sides use Qt, you can use QDataStream. You can have a look at the Qt fortune client/server for a demo.

If one of them doesn't use Qt you might want to use JSON (supported in Qt, and there are many JSON C++ libraries). If you would prefer a binary format, you might want to have a look at msgpack.

Mike
  • 8,055
  • 1
  • 30
  • 44