0
votes

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

2
Please mention the compiler error message that you are seeing. - bittusarkar
Programming by guessing doesn't work, bub! - Lightness Races in Orbit

2 Answers

1
votes

There is a way to do this without using raw memcpy. Having pointer to beginning of memory region, you could do

buf.sgetn(reinterpret_cast<char *>(output), buf.size());

This will copy first n bytes (buf.size() in this case), but also delete them from buffer, leaving non-copied bytes. Might be useful when your buffer is for example class member and you want to reuse it.

0
votes

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());