下面的代码是“C”的做法.. libCurl是一个C库(也有C++包装器):
struct BufferStruct
{
char* buffer;
size_t size;
};
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb; //size is the size of the buffer. nmemb is the size of each element of that buffer.
//Thus realsize = size * sizeof(each_element).
//example: size_t realsize = size * sizeof(char) or size_t realsize = size * sizeof(wchar_t)
//Again: size is the buffer size and char or wchar_t is the element size.
struct BufferStruct* mem = (struct BufferStruct*) data;
//resize the buffer to hold the old data + the new data.
mem->buffer = realloc(mem->buffer, mem->size + realsize + 1);
if (mem->buffer)
{
memcpy(&(mem->buffer[mem->size]), ptr, realsize); //copy the new data into the buffer.
mem->size += realsize; //update the size of the buffer.
mem->buffer[mem->size] = 0; //null terminate the buffer/string.
}
return realsize;
}
这就是做事的 “C” 的方式..
C++的方式如下:
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
std::string* mem = reinterpret_cast<std::string*>(data);
mem->append(static_cast<char*>(data), realsize);
return realsize;
}
然后在某处你的代码做的事:
std::string data; //create the std::string..
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); //set the callback.
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &data); //pass the string as the data pointer.
标准库中有几个函数使用*元素数* x *元素大小*的概念,而不是简单的字节数(例如'calloc')。这是一个回调函数。它所做的就是将提供的数据复制到动态扩展的内存缓冲区中。 – 2014-12-05 23:25:32
参数记录在CURLOPT_WRITEFUNCTION的文档中,我假设您使用的是,尽管您没有这么说...您的摘录是一段名为getinmemory.c的官方libcurl示例代码 – 2014-12-08 23:54:58