C++ objects serialization for Linux
I'm doing a program 开发者_运维百科that needs send and receive data over the network. I never dealt with object serialization. I readed about some recommendations about Boost and Google Protocol Buffers. For use in Linux which is the best?
If you know some other I will appreciate your help.
Thanks.
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.
If you are transferring data over the network, I suggest using a binary form of serialization (not XML or similar). Qt offers classes for that, which allow you to pass any class known to Qt's meta system into a stream of data.
The problem is that C++ does not really support introspection as a language feature, so you'll have to know the data that is to be serialized.
In many cases a length indicator (use big-endian) followed by the data is a good way to serialize data.
精彩评论