如何将非静态成员函数作为回调传递?

2022-01-03 00:00:00 function callback c++ non-static member

 
io_iterator_t enumerator;
kern_return_t   result;
result = IOServiceAddMatchingNotification(
             mNotifyPort,
             kIOMatchedNotification,
             IOServiceMatching( "IOFireWireLocalNode" ),
             serviceMatchingCallback, 
             (void *)0x1234,
             & enumerator );


serviceMatchingCallback((void *)0x1234, enumerator);

如果我将 serviceMatchinCallback 声明为静态,那么它可以工作,但我不希望它是静态的.有没有办法给它传递一个非静态回调函数?

if i declare serviceMatchinCallback as static then it works, but i do not want it to be static. Is there a way to pass it a non-static callback function?

谢谢

推荐答案

你可以让它保持静态,但是除了你想要的任何其他用户数据之外,你还可以使用 userdata 来存储 this 指针(通过打包例如,将它们放入一个结构中),然后通过调用 this->someCallback(其中 this 是存储在用户数据,当然).

You could keep it static, but use the userdata to store the this pointer in addition to whatever other userdata you want (by packing them into a structure, for example) and then call an object-specific callback from the static version by calling this->someCallback (where this is the pointer stored in the userdata, of course).

相关文章