I have been working on libcurl library and there I need to provide the API with a callback function of how it should handle the recieved data. I tried providing it with this callback function as a lambda and it gave me Access violation error, while when I give the same function as a function pointer after defining the function somewhere else it works fine! I want to know what is the difference between the 2 as I thought they were the same thing.
The code used in the following part comes from https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html which is the documentation for libcurl.
Here is the code where I send it the lambda function (This gives access violation error):
int main() {
// Irrelevant initial code...
struct memory {
char* response;
size_t size;
} chunk = { 0 };
curl_easy_setopt(handle, CURLOPT_WRITEDATA, (void*) &chunk);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, // I define a lambda function for the callback...
[](void* data, size_t size, size_t nmemb, void* chunk) -> size_t {
cout << "This function will never get called.. :(" << endl;
size_t realSize = size * nmemb;
memory* mem = (memory*) chunk;
char* ptr = (char*) realloc(mem->response, mem->size + realSize + 1);
if (ptr == NULL) return 0;
mem->response = ptr;
memcpy(&(mem->response[mem->size]), data, realSize);
mem->size += realSize;
mem->response[mem->size] = 0;
return realSize;
});
CURLcode success = curl_easy_perform(handle);
return 0;
}
Here the lambda function was never called thus the line This function will never get called.. :(
never gets displayed in console. It gives access violation error inside the libcurl library in the file called sendf.c in line number 563.
Now here is the same exact thing but I define the function outside:
struct memory {
char* response;
int size;
};
// defined the callback function outside...
size_t cb(void* data, size_t size, size_t nmemb, void* userp)
{
cout << "Working!" << endl;
size_t realsize = size * nmemb;
memory* mem = (memory*)userp;
char* ptr = (char*) realloc(mem->response, mem->size + realsize + 1);
if (ptr == NULL)
return 0;
mem->response = ptr;
memcpy(&(mem->response[mem->size]), data, realsize);
mem->size += realsize;
mem->response[mem->size] = 0;
return realsize;
}
int main() {
// Irrelevant initial code...
memory chunk = { 0 };
curl_easy_setopt(handle, CURLOPT_WRITEDATA, (void*) &chunk);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, cb);
CURLcode success = curl_easy_perform(handle);
return 0;
}
This one worked and it displayed Working!
in the console.
I cannot understand why this 2 are different and why one of them works and the other one does not. Also is it possible to make this work with the lambda function approach as I think it looks much more neater.