我想在非静态成员函数中实现cURL的写回调函数。
调用此方法时会抛出EXE_BAD_ACCESS
错误。但是,如果我在静态方法中使用它,它可以正常工作。
非静态成员函数:
size_t dataFromWebService :: WriteCallback(void *contentsPtr, size_t size, size_t nmemb, string stream, void *classPointer)
{
std::cout<<"Called write call back" <<std::endl;
return static_cast<dataFromWebService*>(classPointer)->WriteCallbackImpl(contentsPtr, size, nmemb, stream);
}
size_t dataFromWebService :: WriteCallbackImpl(void *contentsPtr, size_t size, size_t nmemb, string stream)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = chunk1;//(struct MemoryStruct *)userp;
mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contentsPtr, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
我援引了:
std::string myData;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &dataFromWebService::WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &myData);
调试时我得到了:
size size_t 419
nmemb size_t 140734799803520
realsize size_t 58967881117674880
等效的静态方法是:
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp, struct MemoryStruct *myChunk)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = myChunk;//(struct MemoryStruct *)userp;
mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
我援引了:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
调试值为:
size size_t 1
nmemb size_t 419
realsize size_t 2
MemoryStruct:
struct MemoryStruct
{
char *memory;
size_t size;
};
为什么我为相同数据的非静态成员函数获得更大的nmemb
值?有什么问题?