How can I use a member function pointer in libcurl

I am using libcurl. I upload files inside the class to which I want to see the progress function. I notice that I can set a typical function pointer

curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, progress_func3); 

However, I would like to set it to a function pointer for my class. I can get the code to compile with

 curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, &MyClass::progress_func3); 

and the function progress_func3 is called. The problem is that as soon as he returns, a "buffer overflow" will be detected! an error stating that the program cannot safely continue and execute, and should be terminated. (This is a Microsoft Visual C ++ Runtime Library error window, I am using Visual Studio 2010).

When I use a function, there is no problem, but when I use a pointer to a member function, I will get this error. How can I use a member function pointer in libcurl?

+3
source share
2 answers

A non-static member function requires the this pointer to be invoked. You cannot specify the this pointer with this type of interface, so using a non-static member function is not possible.

You must create a β€œplain C” function as your callback, and that function will call the member function in the corresponding instance of MyClass .

Try something like:

 int my_progress_func(void *clientp, ...) { MyClass *mc = static_cast<MyClass*>(clientp); mc->your_function(...); return 0; // or something else } 

Then:

 curl_easy_setopt(mCurl, CURLOPT_PROGRESSDATA, &your_myclass_object); curl_easy_setopt(mCurl, CURLOPT_PROGRESSFUNCTION, my_progress_func); 

(Obviously, you are responsible for type matching. If you attach anything other than a MyClass pointer to progress data, you are on your own.)

+5
source

You can use boost :: bind (). For instance:

 boost::bind(&MyClass::progress_func3, this); 

is a pointer to a method that returns void and has no arguments. If your answer requires arguments, use placeholders as follows:

 boost::bind(&MyClass::progress_func3, this, _1, _2) 

The this pointer can be replaced by a period with an instance of MyClass .

EDIT: You should be able to use boost :: function <> and function ptr functions relatively interchangeably. For instance:

 typedef boost::function< void (int, short) > Callback; 

equivalently

 typedef void (Callback)(int); 

You may need to add it using a function in between to make the compiler happy. I know that I defined the callback using boost :: function <> and passed it as a regular function pointer.

+1
source

Source: https://habr.com/ru/post/1207628/


All Articles