还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

c++ boost库 序列化与反序列化

来源:清泛原创     2016-06-07 10:44:22    人气:     我有话说( 0 人参与)

1、定义类 结构体序列化函数:template <typename Archive>void serialize(Archive& ar, TOrder & obj, const unsigned int ver...

1、定义类/结构体序列化函数:
template <typename Archive>
void serialize(Archive& ar, TOrder & obj, const unsigned int version = SERIALIZATION_VERSION)
{
        ar & BOOST_SERIALIZATION_NVP(obj.Param) 
                & BOOST_SERIALIZATION_NVP(obj.OrderRef) 
                & BOOST_SERIALIZATION_NVP(obj.UserID);
}
BOOST_SERIALIZATION_SHARED_PTR(TestStruct);
2、save、load函数:
#ifndef STRUCT_SAVE_LOAD_H_
#define STRUCT_SAVE_LOAD_H_
//
#include <string>
#include <fstream>
//
#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/serialization/base_object.hpp"
#include "boost/serialization/list.hpp"
#include "boost/serialization/map.hpp"
#include "boost/serialization/vector.hpp"
#include "boost/serialization/set.hpp"
#include "boost/serialization/string.hpp"
#include "boost/serialization/shared_ptr.hpp"
//
const unsigned int SERIALIZATION_VERSION = 1;
//保存结构体数据
template<typename TemplateStruct> int save(const TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)
{
        try
        {
                std::ofstream ofs(strFileName.c_str());
                boost::archive::xml_oarchive oa(ofs);
                oa << BOOST_SERIALIZATION_NVP(templateStruct);
        }
        catch (...)
        {
                return -1;
        }
        return 0;
}
//从文件加载结构体数据
template<typename TemplateStruct> int load(TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)
{
        try
        {
                std::ifstream ifs(strFileName.c_str());
                boost::archive::xml_iarchive ia(ifs);
                ia >> BOOST_SERIALIZATION_NVP(templateStruct);
        }
        catch (...)
        {
                return -1;
        }
        return 0;
}
//
#endif
3、直接调用save(m_TestStructSet, szFileName) 即可序列化数据列表,load反之。

c++ boost 序列化 反序列化

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: