Reputation: 4848
I am using curl library which returns data to me through a callback function with the prototype below
size_t write_data(void * data, size_t size, size_t nmemb, void * userpointer);
I noticed that if i declare a function fitting this prototype in my class
//file Dialog.h
class Dialog : public QDialog
{
private:
int new_data_callback(void * newdata, size_t size, size_t nmemb, QByteArray * buffer);
}
If i try to use it in my Dialog.cpp
curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTIION, new_data_callback);
I get an error
Invaid use of member (did you forget the '&'?)
If i add static
to my function declaration, it compiles.
static int new_data_callback(void * newdata, size_t size, size_t nmemb, QByteArray * buffer); //ok
Question
Why is static needed in this case?
PS: the classes beginning with Q eg QDialog are part of QT and dont affect the question.
Upvotes: 1
Views: 114
Reputation: 1031
It is because of how functions get invoked. non-static class functions require additional information to be invoked. Namely the this pointer. When you pass new_data_callback
to curl_easy_setopt
this instance specific information is not provided. Thus, curl does not have enough information to invoke the function.
If a class function is defined static it, by definition, cannot access non-static members of a class. Therefore it does not need the additional instance information as above and can be passed to set_easy_setopt
Upvotes: 1
Reputation: 258648
Because a non-static method cannot be called without an instance. Since new_data_callback
is a callback, the only way to attach an instance to it is through a parameter. Making it static
removes the instance restriction.
Upvotes: 3