Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::string with asio::buffer()

I get the following error message when I'm trying to use std::string with boost::asio::buffer:

boost/asio/detail/consuming_buffers.hpp:
In constructor
'boost::asio::detail::consuming_buffers<
        boost::asio::mutable_buffer, boost::asio::const_buffers_1
    >::consuming_buffers(const boost::asio::const_buffers_1 &)':
boost/asio/impl/read.hpp:140:25:  
instantiated from
'boost::asio::detail::read_op<
        boost::asio::basic_stream_socket<boost::asio::ip::tcp>,
boost::asio::const_buffers_1
      , boost::asio::detail::transfer_all_t
      , boost::_bi::bind_t<
            void, boost::_mfi::mf1<void, read_op, const
boost::system::error_code &>
          , boost::_bi::list2<boost::_bi::value<read_op
*>, boost::arg<1> (*)()> 
        > 
    >::read_op(
        boost::asio::basic_stream_socket<boost::asio::ip::tcp>
&, const boost::asio::const_buffers_1
&
      , boost::asio::detail::transfer_all_t
      , boost::_bi::bind_t<
            void, boost::_mfi::mf1<void, read_op, const
boost::system::error_code &>
          , boost::_bi::list2<boost::_bi::value<read_op
*>, boost::arg<1> (*)()>
        >
    )'

[...]

Full source code: http://liveworkspace.org/code/eca749f6f2714b7c3c4df9f26a404d86

like image 829
niXman Avatar asked Nov 01 '10 10:11

niXman


3 Answers

I think the problem is that you are passing a const buffer to async_read instead of a mutable buffer. In the block ending in line 50, boost::asio::buffer(_header) returns a const buffer. You should do something like boost::asio::async_read(s, boost::asio::buffer(data, size), handler), because boost::asio::buffer(data, size) creates a mutable buffer.

Instead of using std::strings for _header and _data, you probably need to use arrays of char, such as:

char* _data;
boost::asio::buffer(_data, strlen(_data));

See reference documentations for buffer and async_read.

like image 173
rturrado Avatar answered Nov 19 '22 10:11

rturrado


You must pass a pointer as the first parameter:

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

std::string request, reply;
auto rsize = boost::asio::buffer(&reply[0], request.size());
like image 7
xunzhang Avatar answered Nov 19 '22 09:11

xunzhang


From the boost::asio::buffer reference documentation:

It seems that std::string could only be passed into an asio::buffer as a const reference.

std::vector<char> should be a better alternative:

std::vector<char> d2(128);
bytes_transferred = sock.receive(boost::asio::buffer(d2));
like image 7
Gang Yin Avatar answered Nov 19 '22 10:11

Gang Yin