gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:16:52 25 4
gpt4 key购买 nike

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

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

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

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

比照Wikipedia: Calling convention

关于C++ CURL 无法正确检索网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com