gpt4 book ai didi

c++ - 了解 BufferStruct + WriteMemoryCallback

转载 作者:行者123 更新时间:2023-11-28 06:32:21 30 4
gpt4 key购买 nike

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com