Passing pointer of class member functions to Windows API
I was developing a small utility in C++, and was using the classes to make my program easy to read and maintain (we all know OOP is better than structured approach most of the time). In one of my class member function, I needed to create a new Window and thus need to populate the WNDCLASSEX structure. Now here is the problem, one of the parameters of this structure contains a function pointer (Windows Callback Procedure). I tried to pass the member function to this, but as I was expecting, I kept getting the compiler error. One dirty option was to make a normal function in that class file and pass its pointer to this call, but I didn’t want to mess my coding with classes and C style functions.
A quick search on Google, and I found the answer (and a solution too). The problem is that member functions also pass a hidden implicit pointer to the class object (this pointer), making the pointer to this function type different and of course OS APIs have no knowledge of how to pass this (unless Windows APIs are written from scratch to support OOP style). The simple solution was to just declare a static member of the class and pass it as parameter. The reason why this works is that in case of state functions, no implicit “this” parameters is passed i.e. the type of member function pointer matched with declared type.
A basic problem with this approach is that static members can’t access the non-static members. Once you know the inner working details, this limitation is obvious (how can it access class data without an object pointer?). There are two workarounds for this, one is to explicitly pass “this” as parameter to the static functions and in the static function use that base class object pointer to access the members. If that’s not possible (in case of API typecast), then one can declare a global pointer to the current object and use that from the static functions (not the best technique, but will work).
If you want to learn more, here are two related very good posts:
http://support.microsoft.com/kb/q102352/
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
Tags: C++, Class, Function Pointer, Member Pointer
This entry was posted
on Tuesday, November 20th, 2007 at 1:51 pm and is filed under Visual C++, Win32 API.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Feedback & Comments
No Responses