【发布时间】:2012-11-24 00:35:53
【问题描述】:
我正在尝试编写一个类以使用 cURL 从 C++ 中的网站获取一些数据。这是该类的一个示例(有一个 Curl* curl_ 数据成员, rawData_ 是一个字符串)。这段摘自实现文件,所有函数都在头文件中声明。
MyClass::MyClass()
{
curl_global_init(CURL_GLOBAL_ALL);
curl_ = curl_easy_init();
curl_easy_setopt(curl_, CURLOPT_URL,
"http://www.google.com");
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &MyClass::writeCallback);
}
MyClass::~MyClass()
{
curl_easy_cleanup(curl_);
curl_global_cleanup();
}
size_t MyClass::writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{
//buf is a pointer to the data that curl has for us
//size*nmemb is the size of the buffer
for (size_t c = 0; c<size*nmemb; ++c)
{
cerr << c << endl;
rawData_.push_back(buf[c]);
}
return size*nmemb; //tell curl how many bytes we handled
}
void MyClass::makeCall()
{
curl_easy_perform(curl_);
}
当我创建 MyClass 的实例并调用 makeCall 时,writeCallBack 函数中存在段错误。即, buf 的大小似乎为 0(当 c = 0 时,它在 buf[c] 的调用中中断)。任何帮助表示赞赏
【问题讨论】:
-
你测试过
buf == this吗? -
这是我应该担心的事情吗?据我所知
buf是通过网络调用传入的;它基本上应该是来自网站的数据。 -
我的意思是,对于 C++ 类方法,
this可以被认为是静态 C 风格函数的隐式第一个参数。如果 curl 调用你提供的回调,就好像它是一个 C 风格的函数(它是),至少调用约定不像 C++ 在调用时在类方法中所期望的那样,并且会发生未定义的事情。