using gzip_compressor with boost::iostreams::filte

2019-08-13 18:32发布

问题:

Code snippet below compiles fine with string but not with <wstring>.

I used filtering_ostream with <string>

const void X::Compress(const wstring& data)
{
    wstring compressedString;
    boost::iostreams::filtering_wostream compressingStream;
    compressingStream.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(boost::iostreams::gzip::best_compression)));
    compressingStream.push(boost::iostreams::back_inserter(compressedString));
    compressingStream << data;
    boost::iostreams::close(compressingStream);

    //...
}

Compilation error:

\boost_x64/boost/iostreams/chain.hpp:258:9: error: no matching function for call to std::list<boost::iostreams::detail::linked_streambuf<wchar_t, std::char_traits<wchar_t> >*, 
std::allocator<boost::iostreams::detail::linked_streambuf<wchar_t, std::char_traits<wchar_t> >*> >::push_backn(std::auto_ptr<boost::iostreams::stream_buffer<boost::iostreams::basic_gzip_compressor<>, std::char_traits<wchar_t>, std::allocator<wchar_t>, boost::iostreams::output> >::element_type*)
         list().push_back(buf.get());
     ^

回答1:

You should write a sequence of bytes to the stream, like sehe mentioned

Something like this:

io::filtering_ostream out;
// ...
out.write(reinterpret_cast<const char*>(&data[0]), data.length() * sizeof(wchar_t));
// ...

In this way you won't have any errors.

Full code:

#include <stdlib.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>

using namespace std;
namespace io = boost::iostreams;

int main(int argc, char* argv[]) {
  wstring wdata(L"SAMPLE_TEXT");

  // compress
  vector<char> packed;
  io::filtering_ostream out;
  out.push(io::gzip_compressor(io::gzip_params(io::gzip::best_compression)));
  out.push(io::back_inserter(packed));
  out.write(reinterpret_cast<const char*>(&wdata[0]), wdata.length() * sizeof(wchar_t));
  io::close(out);

  // decompress
  vector<char> unpacked;
  io::filtering_ostream dec;
  dec.push(io::gzip_decompressor());
  dec.push(io::back_inserter(unpacked));
  dec.write(&packed[0], packed.size());
  io::close(dec);

  // print decompressed data
  wstring result(reinterpret_cast<const wchar_t*>(&unpacked[0]), unpacked.size() / sizeof(wchar_t));
  wcout << result << endl; // prints: SAMPLE_TEXT

  return EXIT_SUCCESS;
}


标签: c++ boost