Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost asio buffer to data

Here I found a way to convert a data into a boost buffer:

#include <memory>
#include <boost/asio.hpp>

int main()
{
    struct { float a, b; } data1;

    auto mutable_buffer = boost::asio::buffer(data);
}

How to do the other way? I mean converting recv_buf.data() into data1?

  socket.receive_from(boost::asio::buffer(recv_buf),
      remote_endpoint, 0, error);
  data1=recv_buf.data() ???????
like image 439
ar2015 Avatar asked Sep 06 '25 03:09

ar2015


1 Answers

You can pack like this:

struct object{ float a, b; } data1[1];
auto mutable_buffer = boost::asio::buffer(data1);

and unpack using memcpy, but only for POD types.

const char* b = boost::asio::buffer_cast<const char*>(mutable_buffer);
object o;
memcpy(&o, b, boost::asio::buffer_size(mutable_buffer));

Live on Coliru

like image 134
ForEveR Avatar answered Sep 07 '25 21:09

ForEveR