cast pointer to member to pointer
I have a problem programming a Windows service where I use a generic CService class to encapsulate the functionality. The Win API requires for the functions RegisterServiceCtrlHandler(...) and StartServiceCtrlDispatcher(...) callback-functions of the form:
VOID WINAPI ServiceMain(
DWORD dwArgc, // number of arguments
LPTSTR *lpszArgv // array of argument string pointers
VOID WINAPI Handler(
DWORD fdwControl // requested control code
When I try to make the Handler and ServiceMain functions members of my class I get type cast errors
Error C2440: '=' : cannot convert from 'void (__stdcall CNTService::*)(unsigned long,char ** )' to 'void (__stdcall *)(unsigned long,char ** )'and
error C2664: 'RegisterServiceCtrlHandlerA' : cannot convert parameter 2 from 'void (unsigned long)' to 'void (__stdcall *)(unsigned long)'
Is there an elegant way to cast a pointer to a member to a simple pointer?
There's no way to convert a pointer to a nonstatic member function to a pointer to an ordinary function. The common trick is to declare the member function as static. Static member functions' addresses are in essence good old C pointers to functions.
As for the second argument: the problem is probably with the calling convention used. You need to cast the void* argument to the correct type explicitly:
typedef VOID (*PF)(DWORD);
func( (PF) your_void_ptr );
I believe that __stdcall is the default calling convention so there's no need to specify it.
I knew about that work-around. I just wanted to be able to use non-static members inside my callback. I resorted to adding a static pointer to "this" to my class initialised with NULL and subsequently set it to the fully initialised object. I think this is a bit untidy, but it's at least workable...
Remember that a pointer to member is not really a pointer but a data structure conatining 2-3 integers so there's no way to convert it to an ordinary pointer without losing data. There is a workaround though: http://gethelp.devx.com/techtips/cpp.../10min0800.asp
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL