How to write boost: asio :: mutable_buffer?

I have code that provides me with a pointer to a buffer and the size of the buffer that I need to fill with data. I present this buffer with an instance of boost::asio::mutable_buffer , but how do I use this buffer correctly (for example, write a string to it, ...) and increase the strength of the buffer boundaries?

Here is some pseudo code:

 size_t some_callback(void *ptr, size_t) { // this function is called by 3rd party return our_handler(boost::asio::mutable_buffer(ptr, size)); } size_t our_handler(const boost::asio::mutable_buffer &buffer) { const std::string test("test"); // How do I write this string into my buffer? return test.size(); } 
+4
source share
1 answer

boost::asio::buffer_cast<>() is what you should use to access the pointer used by the buffer. boost::asio::buffer_size() is what you should use in order to access the size used.

eg.

 const std::string test("test"); const size_t len = std::min(boost::asio::buffer_size(mybuf), test.length()); memcpy(boost::asio::buffer_cast<void *>(mybuf), test.c_str(), len); const std::string test2("test"); boost::asio::mutable_buffer offset = mybuf + len; const size_t len2 = std::min(boost::asio::buffer_size(offset), test2.length()); memcpy(boost::asio::buffer_cast<void *>(offset), test.c_str(), len2); boost::asio::mutable_buffer offset2 = offset + len2; 

See also:

+5
source

Source: https://habr.com/ru/post/1487533/


All Articles