使用boost库进行序列化+压缩的问题

时间:2016-06-20 13:48:21

标签: c++ opencv serialization boost

我遇到了将对象压缩为字符串然后使用boost C ++库将该数据序列化到磁盘的问题。 这是从我之前提出的问题here得出的,该问题成功地解决了从OpenCV库序列化IplImage结构的问题。

我的序列化代码如下:

// Now save the frame to a compressed string
boost::shared_ptr<PSMoveDataFrame> frameObj = frame->getCurrentRetainedFrame();
std::ostringstream oss;
std::string compressedString;
{
    boost::iostreams::filtering_ostream filter;
    filter.push(boost::iostreams::gzip_compressor());
    filter.push(oss);
    boost::archive::text_oarchive archive(filter);
    archive & frameObj;
} // This will automagically flush when it goes out of scope apparently

// Now save that string to a file
compressedString = oss.str();
{
    std::ofstream file("<local/file/path>/archive.bin");
    file << compressedString;
}

//    // Save the uncompressed frame
//    boost::shared_ptr<PSMoveDataFrame> frameObj = frame->getCurrentRetainedFrame();
//    std::ofstream file("<local/file/path>/archive.bin");
//    boost::archive::text_oarchive archive(file);
//    archive & frameObj;

和我的反序列化代码:

// Simply load the compressed string from the file
boost::shared_ptr<PSMoveDataFrame> frame;
std::string compressedString;
{
    std::ifstream file("<local/file/path>/archive.bin");
    std::string compressedString;
    file >> compressedString;
}

// Now decompress the string into the frame object
std::istringstream iss(compressedString);
boost::iostreams::filtering_istream filter;
filter.push(boost::iostreams::gzip_decompressor());
filter.push(iss);
boost::archive::text_iarchive archive(filter);
archive & frame;

//    // Load the uncompressed frame
//    boost::shared_ptr<PSMoveDataFrame> frame;
//    std::ifstream file("<local/file/path>/archive.bin");
//    boost::archive::text_iarchive archive(file);
//    archive & frame;

请注意,两个未压缩的版本(已注释掉)都可以正常工作。 我得到的错误来自boost :: archive :: archive_exception,关于输入流错误。

  • “local / file / path”是我机器上的路径。

1 个答案:

答案 0 :(得分:3)

我天真地将压缩文件分别加载到一个字符串中。 当然,ifstream不知道压缩字符串确实是压缩的。

以下代码修复了问题:

// Simply load the compressed string from the file
boost::shared_ptr<PSMoveDataFrame> frame;
// Now decompress the string into the frame object
std::ifstream file("<local/file/path>/archive.bin");
boost::iostreams::filtering_stream<boost::iostreams::input> filter;
filter.push(boost::iostreams::gzip_decompressor());
filter.push(file);
boost::archive::binary_iarchive archive(filter);
archive & frame;