用于Linux的C ++对象序列化 [英] C++ objects serialization for Linux

查看:569
本文介绍了用于Linux的C ++对象序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个需要通过网络发送和接收数据的程序。我从来没有处理过对象序列化。我阅读了关于Boost和Google协议缓冲区的一些建议。在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.

感谢。

推荐答案

我使用了 Boost.Serialization 来序列化对象并通过套接字传输它们。

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


b $ b

如果Foo不暴露其成员( _foo _bar ),文档对此进行了很好的解释。要序列化 Foo ,请使用 boost :: archive 命名空间中的一个对象:text,binary或xml。 / p>

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;

将归档重建为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.

这篇关于用于Linux的C ++对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆