C ++ CURL没有正确检索网页

时间:2015-11-18 23:00:56

标签: c++ c++11 curl libcurl

我班上有以下三种方法 -

void WebCrawler::crawl()
{
    urlQueue.push("http://www.google.com/");
    if(!urlQueue.empty())
    {
        std::string url = urlQueue.front();
        urlQueue.pop();
        pastURLs.push_back(url);
        if(pastURLs.size()>4000000)
        {
            pastURLs.erase(pastURLs.begin());
        }
        std::string data=getData(url);
        auto newPair= std::pair<std::string, std::string>(url, data);
        dataQueue.push(newPair);
    }

}

std::string WebCrawler::getData(std::string URL)
{
    std::string readBuffer = "";
    CURL *curl = curl_easy_init();

    if(curl)
    {
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WebCrawler::WiteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    }
    return readBuffer;
}

size_t WebCrawler::WiteCallback(char* buf, size_t size, size_t nmemb, void* up)
{

    ((std::string*)up)->append((char*)buf, size * nmemb);
    return size * nmemb;
}

当我从我的类中取出这些方法并将它们作为函数运行时,我的代码正确执行并返回网页内容。但是,只要我将这些方法放入班级,他们就会开始表现不同。当我的WriteCallback被调用时,程序失败并说它无法分配 45457340335435776 字节的数据。对于导致这种变化的原因我感到有点困惑,任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

WebCrawler::WiteCallback是一个非静态方法,这意味着需要传递指向对象(this)的指针。根据ABI,这可以是隐式参数,不用于正常参数传递的寄存器,或其他任何东西。对于您的ABI,看起来对象作为最左边的参数传递(&#34; (WebCrawler *this, char* buf, size_t size, size_t nmemb, void* up)&#34;)。

你不能这样做。要么WebCrawler::WiteCallback静态,要么使用蹦床:

size_t WebCrawler::WriteCallbackTramp(char* buf, size_t size,
                                      size_t nmemb, void* up)
{
    return ((WebCrawler*) up)->WriteCallback(buf, size, nmemb);
}

其中WebCrawler包含缓冲区的成员。

使方法成为静态是更好的解决方案。

C.f。 Wikipedia: Calling convention

相关问题