[英]C++ libcurl seg fault in write callback function
I'm trying to get something done quick and dirty. 我正在尝试快速又肮脏地完成工作。 I saw another SO question and tried to reuse the code.
我看到了另一个SO问题,并尝试重用代码。 I'm hitting a couple rest services (not multithreaded) that return json and when the
CURLOPT_WRITEFUNCTION
is called it throws a seg fault. 我遇到了几个返回json的其他服务(非多线程),并且在调用
CURLOPT_WRITEFUNCTION
时抛出了段错误。 I'm still trying to grasp all the c++ concepts so it's been pretty difficult diagnosing. 我仍在尝试掌握所有c ++概念,因此诊断非常困难。
Here's what I see 这就是我所看到的
static std::string *DownloadedResponse;
static size_t writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{
cout << "In writer callback" << endl;
// Is there anything in the buffer?
if (buffer_in != NULL)
{
cout << "Buffer not null" << endl;
// Append the data to the buffer
buffer_in->append(data, size * nmemb);
cout <<" Buffer appended, seting response" << endl;
DownloadedResponse = buffer_in;
cout << "Set downloadedResponse" << endl;
return size * nmemb;
}
return 0;
}
std::string downloadJSON(std::string URL)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL; // init to NULL is important
std::ostringstream oss;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append( headers, "Content-Type: application/json");
curl_slist_append( headers, "charsets: utf-8");
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPGET,1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writer); // I comment this to display response in stdout.
cout << "calling easy_perform" << endl;
res = curl_easy_perform(curl);
cout << "call made.." << endl;
if (CURLE_OK == res)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if((CURLE_OK == res) && ct)
{
cout << "returning downloaded resposne" << endl;
return *DownloadedResponse;
}
}
else
{
cout << "CURLCode: " << res << endl;
}
}
cout << "Returning null" << endl;
return NULL;
}
Output 输出量
$ ./test-rest calling easy_perform In writer callback Buffer not nullSegmentation fault (core dumped)
How am I improperly using the string in the writer callback function? 如何在writer回调函数中不正确地使用字符串?
您忘记了使用CURLOPT_WRITEDATA传递字符串指针/引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.