
| Last Modification: August 12, 2000 |
Why do I get a compiler error when I try to use a member
function as a callback function?
This is a pretty common problem that arises when you try to use a member
function (one that's a non-static member of a class) as some sort of callback,
like a thread or a window procedure. The problem is really a language issue as
it arises from the fact that in C++, pointers to member functions are different
from pointers to global functions. The reason: each non-static member function
has to receive one extra parameter you don't get to see, but that is very
important: the this pointer. Without it, the function wouldn't be able to
access class members.
There are several workaround, the most common being declaring the function
static. That means that to actually get access to other class members, you need
to figure out a way to give the this pointer to the function. When it
comes to Win32, there's usually an easy way, as most API's that require a
callback provide an extra parameter that they pass directly when they call the
callback function. Another way comes up when you're creating windows, as you
could use the lParam parameter of the CreateWindow() api to pass the value, and
then retrieve it when processing WM_CREATE. Here, a third way pops up: use the
Window Extra bytes to store the pointer, which you can use by allocating enough
space in the cbWndExtra member of the WNDCLASS[EX] structure, SetWindowLong()
and GetWindowLong().
References and samples: