Is it possible to use libcurls CURLOPT_WRITEFUNCTION with a lambda C ++ 11 expression?

I tried using the lambda C ++ 11 expression with CURLOPT_WRITEFUNCTION, but the program crashes at runtime with an access violation. I'm not sure how to look further into this due to a lack of knowledge in C ++ 11, but maybe someone has an idea how to make this work.

Function:

#ifndef CURL_GET_H #define CURL_GET_H #include <curl/curl.h> #include <curl/easy.h> #include <vector> #include <string> std::vector<std::string> curl_get(const char* url) { CURL *curl; CURLcode res; std::vector<std::string> content; auto curl_callback = [](void *ptr, size_t size, size_t nmemb, void *stream) -> size_t { // does nothing at the moment due to testing... return size * nmemb; }; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/aaa.txt"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } return content; } #endif // CURL_GET_H 

Mistake:

Unbehandelte Ausnahme bei 0x000000cc in lpip_dl.exe: 0xC0000005: Zugriffsverletzung bei Position 0x00000000000000cc.

(Access violation at position 0x00000000000000cc)

It happens when curl wants to use a callback:

 wrote = data->set.fwrite_func(ptr, 1, len, data->set.out); 
+8
c ++ lambda c ++ 11 libcurl
source share
2 answers

libcurl is a simple C library, you need to set a callback that can be called from one. That means C ++ funny stuff must first be โ€œC'ifiedโ€ in order to work. As a pointer to an old-style function.

This is also covered in the libcurl FAQ section " Using non-static C ++ functions for callbacks? "

See also: C-style callbacks in C ++ 11

+1
source share

In fact, you can do this by pointing the lambda function to a pointer function. You can first make a typedef to make the cast easier.

 typedef size_t(*CURL_WRITEFUNCTION_PTR)(void*, size_t, size_t, void*); 

Then you use static_cast.

 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, static_cast<CURL_WRITEFUNCTION_PTR>(curl_callback)); 

Note. To convert to a C function pointer, you can use only empty records [].

+7
source share

All Articles