Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ boost::asio::buffer and structures

Tags:

c++

boost-asio

Is there anyway to BASICALLY do the following:

#include <boost/asio.hpp>

struct testStruct{
    int x;
    int y;
};

int main(){
    struct testStruct t;
    boost::asio::buffer b;
    b = boost::asio::buffer(t); 
    return 0;
}

Where it seems to fail is passing 't' into the buffer, 'b'.

like image 477
poy Avatar asked Dec 13 '22 14:12

poy


2 Answers

Use the scatter operation of more than a single buffer:

#include <boost/asio.hpp>

#include <vector>

struct testStruct{
    int x;
    int y;
};

int
main()
{
    struct testStruct t;
    t.x = 5;
    t.y = 7;

    std::vector<boost::asio::const_buffer> buffers;
    buffers.push_back( boost::asio::buffer(&t.x, sizeof(t.x) ) );
    buffers.push_back( boost::asio::buffer(&t.y, sizeof(t.y) ) );

    boost::asio::io_service io_service;
    boost::asio::ip::tcp::socket socket( io_service ); // note not connected!
    std::size_t length = boost::asio::write( socket, buffers );

    return 0;
}

Note you'll need to use a corresponding gather on the receiving side. This gets very tedious with anything more than the contrived example you have presented. Which is why I suggested using a more robust serialization mechanism in your previous question.

like image 76
Sam Miller Avatar answered Dec 28 '22 05:12

Sam Miller


Just Use Boost.Serialization You can get a demo from the http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/examples.html

When you want to send an Object, It is better for you to Serialize it First.

like image 42
AntBean Avatar answered Dec 28 '22 06:12

AntBean