I have a C++ function that makes a call from the libcurl api. The signatures are as follows:
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_WRITEFUNCTION, write_callback);
My implementation is currently this.
extern "C" {
size_t my_callback(char *contents, size_t size, size_t nmemb, void *userp)
{
// ...
data1 = getdata();
data2 = getdata();
return count;
}
}
int MyClass::funcA()
{
// ...
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_callback);
// ...
}
How would I make this callback so that the dataN variables within the callback have access to this instance of my C++ class?
Update:
Using the suggested solution, I have been unable to copy variables from these functions as class variables. I have what now looks like this ...
class MyClass
{
private:
std::string content_;
static size_t handle(char * data, size_t size, size_t nmemb, void * p);
size_t handle_impl(char * data, size_t size, size_t nmemb);
};
size_t Filter::handle(char * data, size_t size, size_t nmemb, void * p)
{
return static_cast<Filter*>(p)->handle_impl(data, size, nmemb);
}
size_t Filter::handle_impl(char* data, size_t size, size_t nmemb)
{
// stops here
content_.append(data, size * nmemb);
return size * nmemb;
}
// within the main()
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Filter::handle);
The problem is that I am now unable to get past the "content_.append" line. But if I change content to be declared locally in this function instead of as a class variable, it continues through. Its as if I am not seeing the class instance.