
simple C/C++ Serialization or deflating or Marshalling user defined data types or objects
September 23, 2010But 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.
- http://www.parashift.com/c++-faq-lite/serialization.html
- http://functionx.com/cpp/articles/serialization.htm
- http://en.wikipedia.org/wiki/Serialization
- http://stackoverflow.com/questions/234724/how-to-serialize-in-c
- http://www.boost.org/doc/libs/1_44_0/libs/serialization/doc/index.html
Advertisement
similar approach for std::map
http://www.cplusplus.com/forum/general/11567/