Search code examples
c++booststreambuf

How to copy streambuf to unsigned char array?


how can I copy data in streambuf to a unsigned char array? The code below have compiler errors:

boost::asio::streambuf buf;
std::ostream os(&buf);
boost::archive::binary_oarchive oa(os);
oa << m_data;

// allocate space for the buffer
unsigned char* output = (unsigned char*)malloc(buf.size());
buf >> output;

The compiler errors are (on the last line):

error C2784: 'std::basic_istream<_Elem,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &&,_Elem *)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &&' from 'boost::asio::streambuf' 1> D:\program\Microsoft Visual Studio 10.0\VC\include\istream(987) : see declaration of 'std::operator >>'

error C2676: binary '>>' : 'boost::asio::streambuf' does not define this operator or a conversion to a type acceptable to the predefined operator


Solution

  • After buffer allocation, you can fill it using memcpy :

    unsigned char* output = (unsigned char*)malloc(buf.size());
    memcpy(output, boost::asio::buffer_cast<const void*>(buf.data()), buf.size());