vendredi 28 septembre 2018

Reference to non-static member function must be called when processing callbacks inside a class

I have the following API code provided by PiGPIO library. Basically it allows you to set a callback function when the state of a pin was changed.

Normally the API looks like this:

typedef void (*gpio_callback_t)(int, int, uint32_t);
int gpioSetAlertFunc(int, gpio_callback_t)

And it can be called like this:

void callback_func(int pin, int NewLevel, uint32_t CurrentTicks)
{
    // Callback process
}

int main()
{
    // Setting up callback function
    gpioSetAlertFunc(10, callback_func)

    // Do stuff while callback will be called independently  
}

Now the code above works perfectly!


The big problem comes when I try to wrap this code in a C++ class. The class shall look like the following:

class Pin
{
public:
    Pin()
    {
        gpioSetAlertFunc(10, this->internal_gpio_callback) );
    }

    void internal_callback_func(int pin, int level, uint32_t tick)
    {
        cout << "New level: " << pin << " " << level;
    }
}

The problem is that the reference to that function is not allowed as it is not a static function. For things to be more complicated, I can't just make the callback function static. That callback function will interact a lot with the rest of the class methods and it's internal variables.

Do you know a workaround for this? Or maybe a dirty hack using pointers or something?

Aucun commentaire:

Enregistrer un commentaire