1

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.

Ender
  • 1,652
  • 2
  • 25
  • 50
  • How can a variable have access to a `class` instance? – 101010 Aug 15 '14 at 00:58
  • 2
    That `userp` sounds like something you give the library so it can later give it back to you. Set that to the address of the `MyClass` instance you want. – dlf Aug 15 '14 at 01:00
  • @dlf - What you're suggesting sounds right, but I have been unable to make that work. I updated the original post showing how I'm now making the calls, but it seems that the class instance is still being unrecognized. – Ender Aug 18 '14 at 21:02
  • @dlf - Ah, there we go, I needed to add 'this' to CURLOPT_WRITEDATA. Thanks. – Ender Aug 18 '14 at 21:10
  • @Ender Ok; glad you solved it. – dlf Aug 19 '14 at 00:07

0 Answers0