清泛IT社区

标题: c++ boost库 序列化与反序列化 [打印本页]

作者: 清泛网    时间: 2016-02-23 17:00
标题: 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(TStopProfitOrder);

2、save、load函数:
  1. #ifndef STRUCT_SAVE_LOAD_H_
  2. #define STRUCT_SAVE_LOAD_H_
  3. //
  4. #include <string>
  5. #include <fstream>
  6. //
  7. #include "boost/archive/text_iarchive.hpp"
  8. #include "boost/archive/text_oarchive.hpp"
  9. #include "boost/archive/xml_iarchive.hpp"
  10. #include "boost/archive/xml_oarchive.hpp"
  11. #include "boost/serialization/base_object.hpp"
  12. #include "boost/serialization/list.hpp"
  13. #include "boost/serialization/map.hpp"
  14. #include "boost/serialization/vector.hpp"
  15. #include "boost/serialization/set.hpp"
  16. #include "boost/serialization/string.hpp"
  17. #include "boost/serialization/shared_ptr.hpp"
  18. //
  19. const unsigned int SERIALIZATION_VERSION = 1;
  20. //保存结构体数据
  21. template<typename TemplateStruct> int save(const TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)
  22. {
  23.         try
  24.         {
  25.                 std::ofstream ofs(strFileName.c_str());
  26.                 boost::archive::xml_oarchive oa(ofs);
  27.                 oa << BOOST_SERIALIZATION_NVP(templateStruct);
  28.         }
  29.         catch (...)
  30.         {
  31.                 return -1;
  32.         }
  33.         return 0;
  34. }
  35. //从文件加载结构体数据
  36. template<typename TemplateStruct> int load(TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)
  37. {
  38.         try
  39.         {
  40.                 std::ifstream ifs(strFileName.c_str());
  41.                 boost::archive::xml_iarchive ia(ifs);
  42.                 ia >> BOOST_SERIALIZATION_NVP(templateStruct);
  43.         }
  44.         catch (...)
  45.         {
  46.                 return -1;
  47.         }
  48.         return 0;
  49. }
  50. //
  51. #endif
复制代码

3、直接调用save(xxxxSet, szFileName) 即可序列化数据列表,load反之。




欢迎光临 清泛IT社区 (https://bbs.tsingfun.com/) Powered by Discuz! X3.3