Why can't I use my C++ member function as a callback (e.g. event handler, action proc)?
Monday, July 21 2003 @ 12:39 PM UTC
Contributed by: witness
Does your compiler complain every time you pass a method as a callback function to a Carbon API, even though you're sure the method's signature is OK?
Depending on what you need, you actually can. It's just not necessarily as simple as installing MacOS. Here are the situations you may have and their solutions:
1) If you have a C++ class with a static member function and want to use that as a callback, you can. There is no problem with that, as long as you don't leave out any little "const" or otherwise choose the wrong data type for one of the parameters.
2) If you have a C++ class with a non-static or even virtual member function, you can't directly use it as a callback. The reason for this is that such functions depend on one particular object they belong to (if they don't, they should be static), and MacOS has no way of carrying along the name of the object the function belongs to (C++ internally passes an additional parameter with the "this" pointer, but every compiler does this differently and thus Apple can't rely on it).
However, with a little trickery, you can help MacOS. Simply declare a static function to be the callback function in your class. Then, when installing your callback, pass a pointer to the object in the "refCon" or "userData" parameter that most callbacks have. Now, all your callback has to do is to extract the object pointer from the userdata, cast it to the right type and call its virtual callback function.