写回调函数中的C ++ libcurl seg错误

时间:2014-08-11 18:36:52

标签: c++ json rest curl libcurl

我正在努力让事情快速而肮脏。我看到另一个SO question并试图重用代码。我正在点击一些返回json的休息服务(不是多线程),当调用CURLOPT_WRITEFUNCTION时它会抛出一个seg错误。我仍然试图掌握所有的c ++概念,因此诊断起来非常困难。

这是我看到的

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;
}

输出

$ ./test-rest
calling easy_perform
In writer callback
Buffer not nullSegmentation fault (core dumped)

我如何在编写器回调函数中不正确地使用字符串?

1 个答案:

答案 0 :(得分:0)

您忘记使用CURLOPT_WRITEDATA传入字符串指针/引用。