Wednesday, April 2, 2008

callback function

callback? function is called with function pointer. that's all?!

How to Implement a Callback to a static C++ Member Function ?
This is the same as you implement callbacks to C functions. Static member functions do not need an object to be invoked on and thus have the same signature as a C function with the same calling convention, calling arguments and return type.

How to Implement a Callback to a non-static C++ Member Function ?
The Wrapper Approach
Pointers to non-static members are different to ordinary C function pointers since they need the this-pointer of a class object to be passed. Thus ordinary function pointers and non-static member functions have different and incompatible signatures! If you just want to callback to a member of a specific class you just change your code from an ordinary function pointer to a pointer to a member function. But what can you do, if you want to callback to a non-static member of an arbitrary class? It's a little bit difficult. You need to write a static member function as a wrapper. A static member function has the same signature as a C function! Then you cast the pointer to the object on which you want to invoke the member function to void* and pass it to the wrapper as an additional argument or via a global variable. If you use a global variable it is very important, that you make sure that it will always point to the correct object! Of course you've also got to pass the calling arguments for the member function. The wrapper casts the void-pointer to a pointer to an instance of the corresponding class and calls the member function.

No comments: