作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
struct BufferStruct { char * buffer; size_t size; }; // This is the function we pass to LC, which wr
我使用以下代码成功地使用 C 和 libcurl 发出了 json-rpc 请求 #include #include #include #include void post_rpc(CURL
我是一名优秀的程序员,十分优秀!