I am writing a program where I have defined an event handler function as a class member function in file 'one.cpp'. My custom http client is defined in other file 'second.cpp'.
Initially I had written curl logic inside one.cpp
curl_easy_setopt( m_curl, CURLOPT_WRITEFUNCTION, EventHandler );
curl_easy_setopt( m_curl, CURLOPT_WRITEDATA, (void*) &eventHandlerInfo );
Here EventHandler is a function to handle an event. EventHandlerInfo is an structure
size_t EventHandler( void* ptr,
size_t size,
size_t nmemb,
EventHandlerInfo* eventHandlerInfo )
This code was working but later we decided to convert one.cpp from c-style to class based impl along with integration of curl from second.cpp. (using second.h inside one.cpp)
Finally, we now have one.cpp which has member function EventHandler and secrond.cpp with Get request wrapper with curl logic. Need to call that wrapper in one.cpp
I have tried 3 ways but none of them worked.lllll
Can anyone suggest any way? It would be helpful.
The usual trick goes something like this:
class CurlWrapper {
size_t WriteHandler(char *ptr, size_t size, size_t nmemb);
static size_t WriteHandlerTrampoline(
char *ptr, size_t size, size_t nmemb, void *userdata) {
auto self = static_cast<CurlWrapper*>(userdata);
return self->WriteHandler(ptr, size, nmemb);
}
};
curl_easy_setopt( m_curl, CURLOPT_WRITEFUNCTION, WriteHandlerTrampoline);
curl_easy_setopt( m_curl, CURLOPT_WRITEDATA, this);
That is, you register a static member function and pass this
for user-defined pointer. The static function recovers the object pointer and calls the "real" handler, implemented as "normal" non-static member function.