boost binary_iarchive 读取的数据不正确

incorrect data from boost binary_iarchive read

我正在尝试从二进制文件中读取自定义数据

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

struct Data 
{
    int xs, ys;
    double ullat, ullon, lrlat, lrlon;
    double minval, maxval;

   // and some vector of floats
};

namespace boost { 
namespace serialization {

template <class Archive>
void
serialize (Archive& ar, Data& d, const unsigned int version)
{
    ar & d.xs & d.ys;
    ar & d.ullat & d.ullon & d.lrlat & d.lrlon;
    ar & d.minval & d.maxval;
}

} // namespace serialization
} // namespace boost

int main (void)
{
    std::ifstream fin ("test.bin", std::ios::in | std::ios::binary);

    // the binary file was not created by boost serialization library. No header information
    boost::archive::binary_iarchive arc (fin, boost::archive::no_header); 

    Data d;
    arc >> d;
}

在此之后,d 包含垃圾值(巨大的 -ve 或 +ve 数字)。

如果我使用 fstream::read 按照 d 的布局读取文件,我会得到正确的值。我无法弄清楚这里发生了什么。正如我在代码中评论的那样,二进制文件是由 boost 序列化库创建的 而不是 。因此使用 no_header 标志。

我使用十六进制查看器工具(linux 上的 ghex)检查了二进制文件,fstream::read 返回了正确的值。这里可能出了什么问题?

我正在使用 gcc-8.3 和 VS2017 with boost 1.70 和 c++17

As I commented in the code, the binary file was not created by boost serialization library.

在这种情况下,您将无法使用 boost::archive::binary_iarchive 读取文件,除非您的文件碰巧共享完全相同的二进制格式。

您需要为 Boost 调用的 Loading Archive Concept 创建一个新的实现。换句话说,一种与您当前格式匹配的新 archive 类型(至少用于加载)。

Hence using no_header flag.

此标志仅跳过 boost::archive::binary_oarchive 写入的 header 以检查 sizes/endianness 等,但它无法在不知道其格式的情况下读取您的数据。这就是为什么您必须编写自己的存档。