无论如何基本上做以下事情:
#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; }
似乎失败的地方是将’t’传递到缓冲区’b’.
解决方法
使用多个缓冲区的
scatter操作:
#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; }
请注意,您需要在接收方使用相应的聚集.除了你提出的人为例子之外,这一点非常繁琐.这就是I suggested在previous question中使用更强大的序列化机制的原因.