Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda to curl callback function

Tags:

c++

c++11

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.

like image 690
Francisco Aguilera Avatar asked Sep 03 '25 02:09

Francisco Aguilera


1 Answers

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.

like image 62
Sunline Avatar answered Sep 04 '25 18:09

Sunline