simple C/C++ Serialization or deflating or Marshalling user defined data types or objects
September 23, 2010 1 Comment
But is it to use boost or not it is your decision 🙂 It is a good lib. But I find it very handy for small in another way as below;-
// Just a simple serialization in C++ #ifndef CVARIABLELENDATA_HPP #define CVARIABLELENDATA_HPP #include <string> typedef char* BuffPtr; typedef size_t BuffLen; class CVariableLenData { public: //Serilizes data members to a char buffer void Serialize(BuffPtr &ptr, BuffLen len, BuffLen &writelen) const; //DeSerilizes from a char buffer & constructs an object static CVariableLenData* DeSerialize(const BuffPtr ptr, BuffLen len); void SetData(std::string& str); void SetData(int& val); CVariableLenData(); private: int m_some_int; // fixed length std::string m_some_str; // variable length CVariableLenData(const CVariableLenData&); }; #endif //CVARIABLELENDATA_HPP // Source file #include <cstdio> #include "CVariableLenData.h" using namespace std; CVariableLenData::CVariableLenData():m_some_int(0),m_some_str(){} void CVariableLenData::Serialize(BuffPtr &ptr, BuffLen bufflen, BuffLen& writelen) const { if(!ptr) return; writelen = _snprintf (ptr, bufflen,"%d", m_some_int); *(ptr+writelen) = ' '; // after each numeric value add an space size_t len = writelen + 1; // now write the string // copy length writelen = _snprintf ( (ptr+len), bufflen,"%u", m_some_str.length()); *(ptr + len ) = ' '; len = len + writelen + 1; // Copy the data memcpy( (ptr+len), m_some_str.c_str(), m_some_str.length()); writelen = len; return; }
Some links.