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反之。
上一篇:error LNK2019: 无法解析的外部符号 __imp__PlaySoundW@12,该符号在函数 "long __stdcall WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@@YGJPAUHWND__@@IIJ@Z) 中被引用
下一篇:vc/mfc *通配符 批量删除文件