C++CURL无法正确检索网页

C++ CURL not retrieving webpage properly

本文关键字:检索 网页 C++CURL      更新时间:2023-10-16

我的类中有以下三个方法-

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字节的数据。我有点困惑是什么导致了这种变化,任何帮助都将不胜感激。

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

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

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

其中CCD_ 5包含用于缓冲器的成员。

将方法设置为静态是更好的解决方案。

维基百科:调用约定