如何在C++中使用boost库序列化自定义class ?| serialize and deserialize a class in cpp with boost
本文首发于个人博客https://kezunlin.me/post/6887a6ee/,欢迎阅读!
serialize and deserialize a class in cpp
Guide
how to serialize string
size + data
The easiest serialization method for strings or other blobs with variable size is to serialize first the size as you serialize integers, then just copy the content to the output stream.
When reading you first read the size, then allocate the string and then fill it by reading the correct number of bytes from the stream.
with ostream/istream
native way with ostream/istream for example class MyClass with height,width,name fields.
class MyClass {
public:
int height;
int width;
std::string name;
}
std::ostream& MyClass::serialize(std::ostream &out) const {
out << height;
out << ',' //number seperator
out << width;
out << ',' //number seperator
out << name.size(); //serialize size of string
out << ',' //number seperator
out << name; //serialize characters of string
return out;
}
std::istream& MyClass::deserialize(std::istream &in) {
if (in) {
int len=0;
char comma;
in >> height;
in >> comma; //read in the seperator
in >> width;
in >> comma; //read in the seperator
in >> len; //deserialize size of string
in >> comma; //read in the seperator
if (in && len) {
std::vector<char> tmp(len);
in.read(tmp.data() , len); //deserialize characters of string
name.assign(tmp.data(), len);
}
}
return in;
}
overload for operator<< and operator>>
std::ostream& operator<<(std::ostream& out, const MyClass &obj)
{
obj.serialize(out);
return out;
}
std::istream& operator>>(std::istream& in, MyClass &obj)
{
obj.deserialize(in);
return in;
}
with boost serialization
archive file format
- text: text_iarchive,text_oarchive
field - xml: xml_iarchive,xml_oarchive, with
BOOST_SERIALIZATION_NVP(field) - binary: binary_iarchive,binary_oarchive with
stringstreamorfstream.
text archive
change BOOST_SERIALIZATION_NVP(field) to field
xml archive
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
class Camera {
public:
int id;
std::string name;
double pos;
};
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive& archive, Camera& cam, const unsigned int version)
{
archive & BOOST_SERIALIZATION_NVP(cam.id);
archive & BOOST_SERIALIZATION_NVP(cam.name);
archive & BOOST_SERIALIZATION_NVP(cam.pos);
}
} // namespace serialization
} // namespace boost
std::ostream& operator<<(std::ostream& cout, const Camera& cam)
{
cout << cam.id << std::endl
<< cam.name << std::endl
<< cam.pos << std::endl;
return cout;
}
void save()
{
std::ofstream file("archive.xml");
boost::archive::xml_oarchive oa(file);
Camera cam;
cam.id = 100;
cam.name = "new camera";
cam.pos = 99.88;
oa & BOOST_SERIALIZATION_NVP(cam);
}
void load()
{
std::ifstream file("archive.xml");
boost::archive::xml_iarchive ia(file);
Camera cam;
ia & BOOST_SERIALIZATION_NVP(cam);
std::cout << cam << std::endl;
}
void test_camera()
{
save();
load();
}
int main(int argc, char** argv)
{
test_camera();
}
binary archive
void save_load_with_binary_archive()
{
// binary archive with stringstream
std::ostringstream oss;
boost::archive::binary_oarchive oa(oss);
Camera cam;
cam.id = 100;
cam.name = "new camera";
cam.pos = 99.88;
oa & (cam);
# get binary content
std::string str_data = oss.str();
std::cout << str_data << std::endl;
std::istringstream iss(str_data);
boost::archive::binary_iarchive ia(iss);
Camera new_cam;
ia & (new_cam);
std::cout << new_cam << std::endl;
}
binary archive with poco SocketStream
client.cpp
void test_client()
{
SocketAddress address("127.0.0.1", 9911);
StreamSocket socket(address);
SocketStream stream(socket);
//Poco::StreamCopier::copyStream(stream, std::cout);
boost::archive::binary_oarchive oa(stream);
Camera cam;
cam.id = 100;
cam.name = "new camera";
cam.pos = 99.88;
oa & (cam);
}
server.cpp
void run()
{
Application& app = Application::instance();
app.logger().information("Request from " + this->socket().peerAddress().toString());
try
{
SocketStream stream(this->socket());
//Poco::StreamCopier::copyStream(stream, std::cout);
boost::archive::binary_iarchive ia(stream);
Camera new_cam;
ia & (new_cam);
std::cout << new_cam << std::endl;
}
catch (Poco::Exception& exc)
{
app.logger().log(exc);
}
}
notes on std::string
Even know you have seen that they do the same, or that .data() calls .c_str(), it is not correct to assume that this will be the case for other compilers. It is also possible that your compiler will change with a future release.
2 reasons to use std::string:
std::string can be used for both text and arbitrary binary data.
//Example 1
//Plain text:
std::string s1;
s1 = "abc";
s1.c_str();
//Example 2
//Arbitrary binary data:
std::string s2;
s2.append("a\0b\0b\0", 6);
s2.data();
boost archive style
intrusive
private template<class Archive> void serialize(Archive& archive, const unsigned int version)friend class boost::serialization::access;
class Camera {
public:
int id;
std::string name;
double pos;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& archive, const unsigned int version)
{
archive & BOOST_SERIALIZATION_NVP(id);
archive & BOOST_SERIALIZATION_NVP(name);
archive & BOOST_SERIALIZATION_NVP(pos);
}
};
non-intrusive
class Camera {
public:
int id;
std::string name;
double pos;
};
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive& archive, Camera& cam, const unsigned int version)
{
archive & BOOST_SERIALIZATION_NVP(cam.id);
archive & BOOST_SERIALIZATION_NVP(cam.name);
archive & BOOST_SERIALIZATION_NVP(cam.pos);
}
} // namespace serialization
} // namespace boost
boost archive type
shared_ptr
boost::shared_ptr<T> instead of std::shared_prt<T>
and
#include <boost/serialization/shared_ptr.hpp>
Reference
- serializing-a-class-which-contains-a-stdstring
- is-it-possible-to-serialize-and-deserialize-a-class-in-c
- boost serialization
- boost serialization demo
- ibm boostserialization
- fast-data-image-transfer-server-client-using-boost-asio
History
- 20180128: created.
- 20180129: add intrusive,non-intrusive part.
Copyright
- Post author: kezunlin
- Post link: https://kezunlin.me/post/6887a6ee/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
如何在C++中使用boost库序列化自定义class ?| serialize and deserialize a class in cpp with boost的更多相关文章
- [Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- 如何在Webstorm中添加js库 (青瓷H5游戏引擎)
js等动态语言编码最大的缺点就是没有智能补全代码,webstorm做到了. qici_engine作为开发使用的库,如果能智能解析成提示再好不过了,经测试80%左右都有提示,已经很好了. 其他js库同 ...
- 在Linux中创建静态库.a和动态库.so
转自:http://www.cnblogs.com/laojie4321/archive/2012/03/28/2421056.html 在Linux中创建静态库.a和动态库.so 我们通常把一些公用 ...
- 在Linux中创建静态库和动态库
我们通常把一些公用函数制作成函数库,供其它程序使用. 函数库分为静态库和动态库两种. 静态库在程序编译时会被连接到目标代码中,程序运行时将不再需要该静态库. 动态库在程序编译时并不会被连接到目标代码中 ...
- boost库的安装,使用,介绍,库分类
1)首先去官网下载boost源码安装包:http://www.boost.org/ 选择下载对应的boost源码包.本次下载使用的是 boost_1_60_0.tar.gz (2)解压文件:tar - ...
- 在Linux中创建静态库和动态库 (转)
我们通常把一些公用函数制作成函数库,供其它程序使用.函数库分为静态库和动态库两种.静态 库在程序编译时会被连接到目标代码中,程序运行时将不再需要该静态库.动态库在程序编译时并不会被连接到目标代码中,而 ...
- VS2010 安装 Boost 库 1.54
Boost库被称为C++准标准库, 功能很是强大, 下面记录我在VS2010中安装使用Boost库的过程. 首先上官网http://www.boost.org/下载最新的Boost库, 我的版本是1_ ...
- windows上编译boost库
要用xx库,编译boost时就指定--with-xx.例如: # 下载并解压boost_1.58 # 进入boost_1.58目录 bjam.exe toolset=msvc-14.0 --build ...
- C++: Mac上安装Boost库并使用CLion开发
1.下载安装Boost库 官网下载最新版本1.65.0:http://www.boost.org/users/history/version_1_65_0.html 选择UNIX版本: 下载后解压cd ...
随机推荐
- 每日温度(LeetCode Medium难度算法题)题解
LeetCode 题号739中等难度 每日温度 题目描述: 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数.如果之后都不会升高,请在该位置用 0 ...
- e.target与事件委托简例(原生和jQuery的区别)
target定义(英译:目标,目的): target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素.文档或窗口. 语法: event.target event.target.no ...
- 深入理解JavaScript中的作用域、作用域链和闭包
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/qappleh/article/detai ...
- 关于举办【福州】《K8S社区线下技术交流会》的问卷调查
近年来,容器.Kubernetes.DevOps.微服务.Serverless等一系列云原生技术受到越来越多的关注,云原生为企业数字化转型提供了创新源动力,基于云原生技术构建企业技术中台在各行业也 ...
- SQlserver高效分页,还在使用row_number(),top之类的?
row_number() ,还是top 这些分页的方法比较老了,效率不是很高效的, Sqlserve2012就有了,效率对比比较明显,尤其是数据比较大的情况下(我们可以观看查询执行计划) Offset ...
- Mysql数据库(0)习题分析
1.查询表中第二高工资的Id,如果没有,返回NULL.此题的关键是如果遇到Empty set,就必须要返回NULL. (1)使用子查询. offset ) AS SecondHighestSalary ...
- Java基础(二十)集合(2)Collection接口
1.Collection接口通常不被直接使用.但是Collection接口定义了一些通用的方法,通过这些方法可以实现对集合的基本操作,因为List接口和Set接口都实现了Collection接口,所以 ...
- github实用的搜索小技巧
查资源,学习优秀的框架,搜索是一种能力! 作为程序猿开发中最大的同性交友网站,github当之无愧,里面有很多优秀的开源框架,各种技术大佬混迹其中,有他们总结的学习教程,造好的轮子(开发的各种工具,技 ...
- TensorFlow Object Detection API中的Faster R-CNN /SSD模型参数调整
关于TensorFlow Object Detection API配置,可以参考之前的文章https://becominghuman.ai/tensorflow-object-detection-ap ...
- 【EmguCV视频教程】VS2017+EmguCV3.4(C# OpenCV)高清入门视频教程
视频采用VS2017 + EmguCV3.4版本录制,内容类似本人的Python和C++版本,如果需要的朋友可加我咨询,视频共40讲,从按照到读取显示图片,图形预处理,边缘检测,形态学,角点检测,轮廓 ...