【问题标题】:C++ cereal de-serialization trouble with large size vector大尺寸向量的 C++ 谷物反序列化问题
【发布时间】:2018-05-25 18:31:59
【问题描述】:

我希望用cereal,C++序列化库来序列化大尺寸向量。

但是,如果尝试这样做,则会抛出异常“读取失败”+ std::to_string(size)+“来自输入流的字节!读取”+std::to_string(readSize)”。

有没有人知道一个好的解决方案? 我正在使用 VisualStudio 2017。

源代码如下所示。

#include <iostream>
#include <fstream>
#include "include\cereal\cereal.hpp"
#include "include\cereal\archives\binary.hpp"
#include "include\cereal\types\vector.hpp"
#include "include\cereal\types\string.hpp"

void show(std::vector<int> v) {
    for (auto i : v)std::cout << i << ",";
    std::cout << std::endl;
}

int main(void) {

    const std::string file_name = "out.cereal";

    {
        std::vector<int> src;
        // const int STOP = 10;  //OK
        const int STOP = 1000; // NG

        for (int i = 0; i < STOP; i++)src.push_back(i);
        std::cout << "src:" << std::endl;
        show(src);

        std::ofstream ofs(file_name, std::ios::binary);
        cereal::BinaryOutputArchive archive(ofs);
        archive(src);
    }

    {
        std::vector<int> dst;
        std::fstream fs(file_name);
        cereal::BinaryInputArchive iarchive(fs);
        iarchive(dst);
        std::cout << "dst:" << std::endl;
        show(dst);
    }

#ifdef _MSC_VER
    system("pause");
#endif
    return 0;
}

【问题讨论】:

    标签: c++ c++11 visual-c++ serialization cereal


    【解决方案1】:

    您的代码在 Linux 中对我来说很好,所以我认为这与 Windows 上的文本和二进制处理之间的区别有关。检查您在构造输入流时是否通过了std::ios::binary。还将其构造为std::ifstream 而不仅仅是std::fstream

    我认为这可能与 Windows 期望(或添加)Unicode 字节顺序标记有关,这会使序列化程序感到困惑。

    【讨论】:

    • 感谢您的评论。我可以解决这个问题。它需要正确地知道字节顺序。
    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多