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乘以?
他试图展示如何将获取的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/

10-13 03:55