简体   繁体   中英

pass function-pointer to non-static member-function

I am coding a program that will automatically trade at various bitcoin exchanges. Since every exchange has it's on API, i made a wrapper class for every API that represents the exchange:

class BITSTAMP : public EXCHANGE {
    public:
       int callbackFunction(int parameter)
       {
       //code
       }
}

the callback function is supposed to handle the JSON-string that the server sends as reply.

i am using the curl library to communicate with the server and i need to pass curl a function-pointer to my callback-function like this:

curl_easy_setopt(CURLOPT_WRITEFUNCTION, functionPointer);

(functionPointer being a normal static function that is implicitly converted to a pointer)

But since BITSTAMP::callbackFunction() is a non-static member (and i can not make it static), i don't know how to pass a pointer to curl :( My compiler suggests to use &BITSTAMP::callbackFunction but obviously it can not be called without an instance -> segfault

Does anyone know how to do this?

The function that you supply to CURLOPT_WRITEFUNCTION needs to match this prototype:

size_t function(char *ptr, size_t size, size_t nmemb, void *userdata);

The parameter "userdata" is anything you specify with CURLOPT_WRITEDATA , so you can make the instance the "userdata" parameter, in which case the body of your function can do:

 BITSTAMP* instance = static_cast<BITSTAMP*>(userdata);
 int parameter = // ...
 instance->callbackFunction(parameter);

.. in order to invoke the member function. (While it is true that C++ supports pointers to member functions, a member function pointer wouldn't help you here, since you still need an instance in order to dereference it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM