I've used Boost.Serialization to serialize objects and transmit them over a socket. It's a very flexible library, objects can be serialized intrusively if you have access to them
class Foo
{
public:
template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & _foo;
ar & _bar;
}
int _foo;
int _bar;
};
or non-intrusively if you don't have access to the object you need to serialize
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive& ar, Foo& f, const unsigned int version)
{
ar & f._foo;
ar & f._bar;
}
} // namespace serialization
} // namespace boost
There are tricks to serialize Foo if it does not expose its members (_foo
and _bar
here), the documentation explains this quite well. To serialize Foo
, you use an object in the boost::archive
namespace: text, binary, or xml.
std::stringstream ss;
boost::archive::text_oarchive ar( ss );
Foo foo;
foo._foo = 1;
foo._bar = 2;
ar << foo;
reconstructing the archive into a Foo object is done like so
boost::archive::text_iarchive ar( ss );
Foo foo
ar >> foo;
Note this example is fairly trivial, and obviously when you introduce a network you'll be using sockets and buffers.