0

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

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"

谁能帮我理解出了什么问题?

4

1 回答 1

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();
    }
}
于 2016-08-24T16:28:07.417 回答