oop - Packet serialization in C++ -


i have project packet serialization of several different types(packet1, packet2...). extend packetheader class , own serialization

this approach seems messy , error-prone, number of fields grows.

is there cleaner , more oop & c++ way serialization(without 3rd-party library)?

class packetheader {     uint8_t type;     uint32_t id;     uint32_t seqnum;      virtual void serialize(uint8_t *buf, size_t size) {         int offset = 0;         packetheader n;         n.type = type;         n.id = htonl(id);         n.seqnum = htonl(seqnum);         memcpy(buf + offset, &(n.type), sizeof(n.type));         offset += sizeof(n.type);         memcpy(buf + offset, &(n.id), sizeof(n.id));         offset += sizeof(n.id);         memcpy(buf + offset, &n.seqnum, sizeof(n.seqnum));         offset += sizeof(n.seqnum);     } }  class packet1 : public packetheader {     uint32_t payload;      virtual void serialize(uint8_t *buf, size_t size) {         int offset = packetheader::size();         packetheader::serialize(buf, size);         memcpy(buf + offset, &n.payload, sizeof(n.payload));         offset += sizeof(n.payload);     } } 

doing serialization natively on structures , classes data members requires feed offset, size, , type information each member serializer. that's source of "messy" aspect , can't avoid no matter how elegant design.

there helper libraries can provide structure they're syntax candy , still pretty hard maintain number of message types grows.

instead recommend looking @ systems provide dictionaries -- key/value data objects -- rather using native c++ structure/class data members. use standard serialization formats such json. jsoncpp regarded package this: http://jsoncpp.sourceforge.net/

mostly provide advantage software system scale better grows , won't become exponential maintenance headache.

if binary serialization desired, take @ bson, messagepack, google protocol buffers, , apache thrift. offer libraries or bindings c++.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -