Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind() *this to class member function to make a callback to C API

Tags:

c++

std

boost

Is there a way to use boost or std bind() so I could use a result as a callback in C API? Here's sample code I use:

#include <boost/function.hpp>
#include <boost/bind/bind.hpp>

typedef void (*CallbackType)();

void CStyleFunction(CallbackType functionPointer)
{
    functionPointer();
}

class Class_w_callback
{
public:
    Class_w_callback()
    {
        //This would not work
    CStyleFunction(boost::bind(&Class_w_callback::Callback, this));
    }
    void Callback(){std::cout<<"I got here!\n";};
};

Thanks!

like image 566
Ivan Lebediev Avatar asked Dec 20 '22 00:12

Ivan Lebediev


1 Answers

No, there is no way to do that. The problem is that a C function pointer is fundamentally nothing more than an instruction address: "go to this address, and execute the instructions you find". Any state you want to bring into the function has to either be global, or passed as parameters.

That is why most C callback APIs have a "context" parameter, typically a void pointer, that you can pass in, and just serves to allow you to pass in the data you need.

like image 116
jalf Avatar answered Feb 15 '23 23:02

jalf