c++ - 了解 BufferStruct + WriteMemoryCallback

标签 c++ function libcurl

struct BufferStruct
{
char * buffer;
size_t size;
};

// This is the function we pass to LC, which writes the output to a BufferStruct
static size_t WriteMemoryCallback
(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;

struct BufferStruct * mem = (struct BufferStruct *) data;

mem->buffer = realloc(mem->buffer, mem->size + realsize + 1);

if ( mem->buffer )
{
memcpy( &( mem->buffer[ mem->size ] ), ptr, realsize );
mem->size += realsize;
mem->buffer[ mem->size ] = 0;
}
return realsize;
}

我找到了这个 here

他来这里干什么?特别是通过乘以那些 size_t's? 他试图展示如何将您获得的 html 代码导出到文件中。 为什么有必要编写这样一个复杂的(对我来说)函数? 如果有人可以解释或发布一些可以帮助我理解这一点的资源,谢谢 :)

最佳答案

下面的代码是“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.

关于c++ - 了解 BufferStruct + WriteMemoryCallback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27326229/

相关文章:

javascript - 如何使用 javascript 函数创建可以调用 javascript 函数的 polymer 元素

ios - Swift 将数组中的所有元素加在一起

PHP 类具有来自 Traits 的冲突构造函数定义

c - Windows 链接到 libcurl_a.lib

c++ - OpenGL 中的视差映射故障

c++ - std::array 编译时间扣除

c++ - 登录网站,然后访问该网站的另一部分

c++ - Curlpp 的问题

c++ - 带有 -isysroot 的 gcc 创建包含以等号 "="开头的包含路径并且编译失败

c++ - 为 ISO 8859-1 实现 basic_string<unsigned char>