Archived

This topic is now archived and is closed to further replies.

Win32 Wrapper - Hooks / Function Pointers over Inheritance?

This topic is 4947 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m in the process of coding a Win32 wrapper (more like a whole library for all the controls I''m wrapping). A brick wall has showed its ugly face however, involing ways to find out what a control is "doing". A "main" message pump is used, which forwards messages onto individual controls. That control than handles the messages forwarded onto it (or doesn''t) and everyone is happy. By now, the problem should be fairly clear (hopefully). How do you allow the program to interact with, say, a button without inheriting it and creating your own? The button''s message handler is in the library, so you can''t change that without inheriting it and drafting your own. As of now, the only solution I''ve been able to come up with has been function pointers. Instead of inheriting, you just set the function you want the button to call when a specific event is fired. Example: ButtonBeginGame->SetClickEvent(BeginGameButtonClickEvent); ButtonHelp->SetClickEvent(HelpButtonClickEvent); etc. etc. The problem (as far as I can tell) is that those functions would have to be in the global namespace and thusly, to a degree, breaking OO. Anyone coded something similar with a different solution?

Share this post


Link to post
Share on other sites
The typical solution generally involves functors of some sort. For pre-packaged versions consider looking into boost or loki.

(Or if you''re a compiler writer, you can hack the language some.)

Share this post


Link to post
Share on other sites
Please use functors. Hooking the various aspects of a class is far preferable to inheritance in terms of reuse. Rolling your own functors may prove to be useful if you don''t want your users to depend on Boost or Loki.

An example is embedded in Event.hpp. I wanted to support operator== on functors so I had to roll my own. It is a fun review of C++. You''ll want to check out the base Handler class as well.

Share this post


Link to post
Share on other sites
You can see a fairly complete function pointer approach here. The callback gets sent a pointer to the button, and the button has a pointer that can be set to the calling object, and the callback can therefore use ''->'' on the object''s internals or simply forward itself to a public or private member function of the object using that pointer. It is even easy to change button handlers in midstream.

http://www.randommonkeyworks.com/Programming/WinAPI_ver2/Project_Begin.html

David

Share this post


Link to post
Share on other sites