samedi 7 octobre 2023

How to use a class based member function as an callback function in curl_easy_setopt() in cpp

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

  1. Pass function pointer as an argument to GET wrapper in one.cpp
  2. Separated event handler from one.cpp to create a class based functor overloaded with () operator. Used that directly in second.cpp. I didn't get any error but callback is not working
  3. Created a generalized lambda in second.cpp and directly passed it to curl_easy_setopt. Callback didn't work

Can anyone suggest any way? It would be helpful.

Aucun commentaire:

Enregistrer un commentaire