0

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

venusisle
  • 113
  • 2
  • 10

2 Answers2

1

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.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Kma
  • 41
  • 1
  • 6
0

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());
mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • Thanks, on the other way, do you know how can I copy the data in an unsigned char * array to the buf? I know I can use memcpy, however, are there simpler ways? – venusisle Feb 23 '15 at 20:12