how to pass a non static-member function as a callback?

后端 未结 8 614
深忆病人
深忆病人 2020-12-07 01:59

 
io_iterator_t enumerator;
kern_return_t   result;
result = IOServiceAddMatchingNotification(
             mNotifyPort,
             kIOMatchedNotification,
             


        
8条回答
  •  离开以前
    2020-12-07 02:27

    The prototype for IOServiceMatchingCallback is not compatible with a non-static class method (and technically is not compatible with a static class method either), so you are not going to be able to use that.

    But luckily IOServiceAddMatchingNotification supports a context pointer (or as they call it, a refCon) which will allow you to create a thunk that does not rely on global data.

    You need to define a callback with compatible linkage (i.e. extern "C"). This function will cast your refCon to your object pointer and then forward the call to your instance method:

    extern "C"
    void io_callback(void *refcon, io_iterator_t iterator)
    {
        myclass *c = static_cast(refcon);
        c->real_callback(iterator);
    }
    

    Then, when you call IOServiceAddMatchingNotification, make sure to pass a pointer to your object for refCon (here I'm assuming you call IOServiceAddMatchingNotification from a member function and you have a this pointer):

    result = IOServiceAddMatchingNotification(
                 mNotifyPort,
                 kIOMatchedNotification,
                 IOServiceMatching( "IOFireWireLocalNode" ),
                 serviceMatchingCallback, 
                 this,
                 &enumerator );
    

提交回复
热议问题