simple C/C++ Serialization or deflating or Marshalling user defined data types or objects

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.

Advertisements

About yadab das
Software Developer{writing,debugging,documenting} source code

One Response to simple C/C++ Serialization or deflating or Marshalling user defined data types or objects

  1. yadab das says:

    similar approach for std::map
    http://www.cplusplus.com/forum/general/11567/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: