你如何在 C++ 中序列化一个对象?
我有一个小的对象层次结构,我需要通过套接字连接序列化和传输这些对象.我需要序列化对象,然后根据它的类型反序列化它.在 C++ 中有没有一种简单的方法可以做到这一点(就像在 Java 中一样)?
是否有 C++ 序列化在线代码示例或教程?
明确地说,我正在寻找将对象转换为字节数组,然后再转换回对象的方法.我可以处理套接字传输.
解决方案谈序列化,boost 序列化 API.至于通过网络传输序列化数据,我要么使用伯克利套接字,要么使用 asio 库.>
如果要将对象序列化为字节数组,可以按以下方式使用 boost 序列化器(取自教程站点):
#include #include 类 gps_position{私人的:友元类 boost::serialization::access;模板<类存档>void serialize(Archive & ar, const unsigned int version){和度;和分钟;和秒;}整数度;整数分钟;浮动秒;民众:gps_position(){};gps_position(int d, int m, float s) :度(d)、分(m)、秒(s){}};
实际的序列化非常简单:
#include std::ofstream ofs("filename.dat", std::ios::binary);//创建类实例const gps_position g(35, 59, 24.567f);//保存数据到存档{boost::archive::binary_oarchive oa(ofs);//将类实例写入存档oa<<G;//调用析构函数时存档和流关闭}
反序列化的工作方式类似.
还有一些机制可以让您处理指针的序列化(复杂的数据结构,如 tres 等没有问题),派生类,您可以在二进制和文本序列化之间进行选择.此外,所有 STL 容器都是开箱即用的.
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)?
Are there any C++ serialization online code samples or tutorials?
EDIT: 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.
解决方案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.
Edit:
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
}
Deserialization works in an analogous manner.
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.
相关文章