I am trying to pass a lambda to the CURLOPT_WRITEFUNCTION
.
The function expects a static function, however, I learned from this question that a lambda would be implicitly converted, and I could call the member function from the lambda.
auto callback = [](char * ptr_data, size_t size, size_t nmemb, string * writerData)
->size_t
{
if(writerData == NULL)
return 0;
size_t data_size = size * nmemb;
writerData->append(ptr_data, data_size);
return (int)data_size;
};
CURLcode code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, callback);
This actually compiles, but curl segfaults: Segmentation fault: 11
I pasted the full example here.
The magic is, add the leading "+" at the non-captured lambda expression, which will trigger conversion to plain C function pointer.
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
/* NOTE: Leader '+' trigger conversion from non-captured Lambda Object to plain C pointer */
+[](void *buffer, size_t size, size_t nmemb, void *userp) -> size_t {
// invoke the member function via userp
return size * nmemb;
});
My understanding is, curl_easy_setopt
wants a void*
, not an explicit function type, so the compiler just gives the address of lambda object; if we do a function pointer operation on lambda object, the compiler will return the function pointer from lambda object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With