简体   繁体   中英

Map C++ member function to C callback

In a C++ project I am using a C library to access some hardware. The C-Bindings include callbacks to notify about changes on some input pins. The function for the callback looks like this: void callback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)

In my implementation I have a SensorController class which has a member function that should receive the callback. The member function looks like this void SensorController::pinChanged(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data) .

Now I was wondering, what would be the cleanest way to avoid making the pinChanged function static to be able to assign the function to the callback?

Use the user_data pointer to give you back a pointer to the class that owns the callback. For example.

void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)
{
    static_cast<Example *>(user_data)->Callback(port, interrupt_mask, value_mask);
}

class Example
{
public:

    Example()
    {
        //setup callback here - i dont know what library you're using but you should be able to pass a this pointer as user_data
        init_lib(fictionalparameter1, fictionalparameter2, this);
    }

private:

     void   Callback(char port, uint8_t interrupt_mask, uint8_t value_mask)
     {
         //callback handler here...
     }

     friend void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data);
};

Function that receives callback can only be:

  1. Ordinary function
  2. Static function

Why it can't be a member class function?

It's all about pointers. Pointer to ordinary function or static function is an address to memory. Pointer to a member class function is an offset - number which should be added to object pointer (this) to access the method. [see jv110 comment]

In C++, member functions have an implicit parameter which points to the object (the this pointer inside the member function). Normal C functions can be thought of as having a different calling convention from member functions, so the types of their pointers (pointer-to-member-function vs pointer-to-function) are different and incompatible. C++ introduces a new type of pointer, called a pointer-to-member, which can be invoked only by providing an object. https://isocpp.org/wiki/faq/pointers-to-members#addr-of-memfn

You could use user_data in callback to access class member methods like user1320881 said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM