This question is about boost::asio::buffer
I have a call to send data over a TCP socket. Following is the call:
std::vector<unsigned char> data = GetDataToSend();
boost::asio::async_write(tcp_socket, boost::asio::buffer(data),
[this](const boost::system::error_code & error, std::size_t bytes_sent) {
if (!error && bytes_sent > 0) {
// Success!
}
});
Above is great as long as GetDataToSend
returns a std::vector<unsigned char>
.
But, what if GetDataToSend
returned a uint8_t*
? Isn't it possible to put the uint8_t*
data into boost::asio::buffer
and do an async_write
? Something like below..
uint8_t* data = GetDataToSend();
boost::asio::async_write(tcp_socket, boost::asio::buffer(data),
[this](const boost::system::error_code & error, std::size_t bytes_sent) {
if (!error && bytes_sent > 0) {
// Success!
}
});
Is it that boost::asio::buffer
only operates on std::vector<unsigned char>
s?
How can I create a boost::asio::buffer
object from uint8_t*
? It will be great if I could do this without causing an extra copy if possible.
I am using boost 1.63.
On the page, there are all buffer overloads, one of them is
const_buffer buffer(
const void * data,
std::size_t size_in_bytes);
you could use it but you need to define the size of your buffer. Without this, how can async_write
know how many bytes must be transmitted ? In case of vector
, buffer
knows this size by calling vector::size
method. In case of raw buffers you have to provide this explicitly.
If GetDataToSend
returned pair: pointer to data and its length, you could write:
std::pair<uint8_t*,size_t> GetDataToSend() {
// ...
return result;
}
std::pair<uint8_t*,int> data = GetDataToSend();
boost::asio::async_write(tcp_socket, boost::asio::buffer(data.first, data.second), ...