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

清泛原创
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 序列化 反序列化

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部