如何在C ++中序列化对象? [英] How do you serialize an object in C++?

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

问题描述

我有一个小层次的对象,我需要通过套接字连接序列化和传输。我需要两个序列化对象,然后反序列化它基于它是什么类型。有没有一个简单的方法来做这个在C + +(如在Java中)?

I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what type it is. Is there an easy way to do this in C++ (as there is in Java)?

有没有任何C ++序列化在线代码示例或教程?

Are there any C++ serialization online code samples or tutorials?

编辑:为了清楚起见,我正在寻找将对象转换为字节数组,然后回到对象的方法。我可以处理socket传输。

Just to be clear, I'm looking for methods on converting an object into an array of bytes, then back into an object. I can handle the socket transmission.

推荐答案

谈论序列化, boost serialization API 。至于通过网络传输序列化数据,我将使用Berkeley套接字或 asio库

Talking about serialization, the boost serialization API comes to my mind. As for transmitting the serialized data over the net, I'd either use Berkeley sockets or the asio library.

编辑

如果要将对象序列化为字节数组,可以按以下方式使用boost序列化程序教程网站):


If you want to serialize your objects to a byte array, you can use the boost serializer in the following way (taken from the tutorial site):

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
class gps_position
{
private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & degrees;
        ar & minutes;
        ar & seconds;
    }
    int degrees;
    int minutes;
    float seconds;

public:
    gps_position(){};
    gps_position(int d, int m, float s) :
    degrees(d), minutes(m), seconds(s)
    {}
};

实际的序列化非常容易:

Actual serialization is then pretty easy:

#include <fstream>
std::ofstream ofs("filename.dat", std::ios::binary);

    // create class instance
    const gps_position g(35, 59, 24.567f);

    // save data to archive
    {
        boost::archive::binary_oarchive oa(ofs);
        // write class instance to archive
        oa << g;
        // archive and stream closed when destructors are called
    }

反序列化

还有一些机制允许你处理指针的序列化(复杂的数据结构,比如tres等没有问题),派生类,你可以选择二进制和文本序列化。除此之外,所有的STL容器都是开箱支持的。

There are also mechanisms which let you handle serialization of pointers (complex data structures like tress etc are no problem), derived classes and you can choose between binary and text serialization. Besides all STL containers are supported out of the box.

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

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