c++ - Understanding BufferStruct + WriteMemoryCallback -
struct bufferstruct { char * buffer; size_t size; }; // function pass lc, writes output 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; }
i found here
what trying here? espacially multiplying size_t's? trying show how export html code file. why necesarry write complex (for me) function that? if can explain or post source can me understand :)
this code below "c" way of doing it.. libcurl c library (there c++ wrappers well):
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 size of buffer. nmemb size of each element of buffer. //thus realsize = size * sizeof(each_element). //example: size_t realsize = size * sizeof(char) or size_t realsize = size * sizeof(wchar_t) //again: size buffer size , char or wchar_t element size. struct bufferstruct* mem = (struct bufferstruct*) data; //resize buffer hold old data + new data. mem->buffer = realloc(mem->buffer, mem->size + realsize + 1); if (mem->buffer) { memcpy(&(mem->buffer[mem->size]), ptr, realsize); //copy new data buffer. mem->size += realsize; //update size of buffer. mem->buffer[mem->size] = 0; //null terminate buffer/string. } return realsize; }
that "c" way of doing things..
the c++ way shown below:
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; }
then somewhere in code do:
std::string data; //create std::string.. curl_easy_setopt(curl_handle, curlopt_writefunction, writememorycallback); //set callback. curl_easy_setopt(curl_handle, curlopt_writedata, &data); //pass string data pointer.
Comments
Post a Comment