将std :: string转换为boost :: asio :: streambuf

时间:2017-07-04 11:04:51

标签: c++ boost

如何将std::string转换为boost::asio::streambuf? 任何领导都表示赞赏。

最初我使用boost::asio::read_until(pNetworkConnector->getSocket(), response, "\r\n");初始化boost::asio::streambuf response并将其转换为基础流,即

boost::asio::streambuf* responsePointer = &response;
iResponseStream.rdbuf(responsePointer);

但现在我直接使用像这样的curl std::string

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

并将其用作

curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &readBuffer);

如何将std::string转换为boost::asio::streambufstd::streambuf

1 个答案:

答案 0 :(得分:2)

以下代码显示了如何在std::stringboost::asio::streambuf之间进行转换,请参见online at ideone

#include <iostream>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/buffer.hpp>

int main()
{
   /* Convert std::string --> boost::asio::streambuf */
   boost::asio::streambuf sbuf;
   std::iostream os(&sbuf);
   std::string message("Teststring");
   os << message;

   /* Convert boost::asio::streambuf --> std::string */
   std::string str((std::istreambuf_iterator<char>(&sbuf)),
                    std::istreambuf_iterator<char>());

   std::cout << str << std::endl;
}