【问题标题】:Cereal Binary Archive Serialize/Deserialize谷物二进制存档序列化/反序列化
【发布时间】:2016-12-31 20:59:58
【问题描述】:

我正在使用以下代码尝试将对象序列化/反序列化为二进制数据:

MyDTO dto1;    
std::ostringstream os(std::stringstream::binary);
{
    cereal::BinaryOutputArchive oarchive(os); // Create an output archive
    oarchive(dto1);
}

MyDTO dto2;

std::istringstream is(os.str(), std::stringstream::binary);
{
    cereal::BinaryInputArchive iarchive(is); // Create an input archive
    try {
        iarchive(dto2);
    }
    catch (std::runtime_error e) {
        e.what();
    }
}

代码运行时,捕获到异常并显示消息:

"Failed to read 8 bytes from input stream! Read 0"

谁能帮我理解怎么回事?

【问题讨论】:

  • 你应该向我们展示输入文件
  • 没有输入文件,我正在读写字符串。
  • istringstream 构造已修复,现在似乎可以正常工作了。

标签: c++ serialization deserialization cereal


【解决方案1】:

您的输入存档 iarchive 没有可读取的数据,因为 is 为空。您应该首先使用输出存档写入stringstream,然后使用相同的字符串流为iarchive 读取(我猜这就是您想要做的)

你应该试试下面的方法(我没有测试过):

MyDTO dto1;    
std::stringstream os(std::stringstream::binary);
{
    cereal::BinaryOutputArchive oarchive(os); // Create an output archive
    oarchive(dto1);
}

MyDTO dto2;

{
    cereal::BinaryInputArchive iarchive(os); // Create an output archive
    try {
        iarchive(dto2);
    }
    catch (std::runtime_error e) {
        e.what();
    }
}

【讨论】:

  • 在简化我的代码时,我忽略了将 ostream 读回 istream 的位置。问题已更新。
  • 您的所作所为与我向 IMO 展示的内容没有什么不同。你觉得我的解决方案有什么问题吗?
  • 好吧问题更新了,但现在没有问题了:)
  • 您的解决方案并不完全正确,但它确实帮助表明我没有正确构建 istringstream。
猜你喜欢
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 2011-06-08
  • 2010-11-08
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多