首页 > 解决方案 > 使用不同的 Boost 版本会影响序列化和反序列化吗?

问题描述

我正在使用 Boost 进行二进制序列化和反序列化的 C++ 项目。Boost 版本 1.61 中已经存在序列化功能我使用 Boost 版本 1.77 添加了整个反序列化功能,现在我在读取二进制文件时遇到了问题。所以,我的问题是这种反序列化版本的差异如何影响这个过程?因为我无法正确读取二进制文件。

使用 Boost 版本 1.61 进行序列化的代码

#include <boost/archive/binary_oarchive.hpp>
#include <fstream>
#include <string>

class Frame{
public:
    std::string str;
};
template <typename Archive>
void serialize(Archive& ar, Frame& f, const unsigned int version) {
    ar& f.str;
}

uint32_t main () {
    Frame f={"Frame example"};
    std::ofstream ofs;
    ofs.open("BinaryFile.bin",std::ios::out, std::ios::binary);
    boost::archive::text_oarchive write(ofs,boost::archive::no_header);
    write << f;
    ofs.close();
}

使用 boost 1.77 版本进行反序列化的代码

#include <boost/archive/binary_iarchive.hpp>
#include <fstream>
#include <string>

class Frame{
public:
    std::string str;
};
template <typename Archive>
void serialize(Archive& ar, Frame& f, const unsigned int version) {
    ar& f.str;
}

uint32_t main () {
    Frame f;
    std::ofstream ofs;
    ofs.open("BinaryFile.bin",std::ios::in, std::ios::binary);
    boost::archive::text_oarchive read(ofs,boost::archive::no_header);
    read >> f;
    ofs.close();
}

这只是一个示例代码,我使用的框架不同但方法相同。

标签: c++boost

解决方案


编码稳定性不是 boost 序列化本身的属性,而是在每个存档的基础上处理。

您可以get_library_version()在存档上使用来检查增强版本之间的兼容性。

返回一个无符号整数,其中包含序列化库的当前版本号。每次以这样的方式更改库时,此数字都会增加,从而可以更改某些类型的序列化。[...]


推荐阅读