But if you try to pass it the address of a C++ object member function, like so:
1: 2: 3: 4: 5: 6: 7: |
class MyTimer {
...
void MyTimerProc();
...
}
int nTimerID = SetTimer( NULL, 1234, 1000, MyTimerProc );
|
...you will get a compiler error like:
error C2643: illegal cast from pointer to member
error C2664: 'SetTimer' : cannot convert parameter 4 from ... to ...
The reason has to do with the calling convention used for member functions. In your program, when you call a member function, the compiler pushes the this pointer on the stack along with the other parameters. But the API functions that will be using your callback expect to use the simpler calling convention.
Let's start with a program that defines and uses a CBaseTimer object. The following works because it uses a simple global function rather than a member function as the callback:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: |
{{{{ Example 1 -- using a global (non-member) function }}}}
#include <windows.h>
#include <stdio.h>
#include <Mmsystem.h>
#pragma comment(lib, "Winmm.lib" )
void CALLBACK MyTimerProc( UINT, UINT, DWORD, DWORD, DWORD ) {
printf( "---------- timer tick ----------- \r\n");
}
class CBaseTimer {
public:
CBaseTimer(int nIntervalMs) { m_nIntervalMs=nIntervalMs;}; // ctor
~CBaseTimer() { Kill(); }; // dtor
int m_nID;
long m_nIntervalMs;
void Start() { // TBD: Check if 0 (failed)
m_nID= timeSetEvent( m_nIntervalMs, 10,
MyTimerProc, 0, TIME_PERIODIC );
}
void Kill() {
::timeKillEvent( m_nID );
}
};
//------------------------------------- main() -- example usage of the object
int main(int argc, char* argv[])
{
CBaseTimer cTimer( 1000 );
cTimer.Start();
for (int j=0; j< 40; j++) {
Sleep(100);
printf( "Hi there\r\n" );
}
return 0;
}
|
But if you want the callback to be a member function:
1: 2: 3: 4: 5: |
class CBaseTimer {
...
void CALLBACK MyTimerProc( UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2 );
...
|
You will get the dreaded compiler error. The common/documented way to avoid this is to make the callback into a static member function.
1: 2: 3: 4: 5: |
class CBaseTimer {
...
static void CALLBACK MyTimerProc( UINT, UINT, DWORD, DWORD, DWORD ); //<<--- note: "static"
...
|
The "static" specifier indicates that it is common code used by all instances of the object and that the code cannot directly access non-static members. It is basically a global function, just like in Example 1; the calling convention is the same (no this pointer on the stack).
But what's the point of having a class member that can't access class members?
In this little base class, we have hard-coded the action that takes place on the timer event. But you would certainly want to derive objects that could do different things.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: |
{{{{ Example 2: Failing attempt to use a member function }}}}
class CMsgTickTimer: public CBaseTimer {
public:
CMsgTickTimer( int nIntervalMs, LPCSTR szMsg ) {
m_nIntervalMs= nIntervalMs;
strncpy( m_szMsg, szMsg, sizeof(m_szMsg) );
}
char m_szMsg[100];
static void CALLBACK MyTimerProc( UINT, UINT, DWORD, DWORD, DWORD ) {
printf( "------ %s ------- \r\n", m_szMsg ); // <<-- ERROR
}
};
|
The MyTimerProc function is attempting to access m_szMsg, a per-instance (non-static) value, but it is trying to do that in a static member function. And that's not allowed. Thus, the compiler error:
error C2597: illegal reference to data member 'CMsgTickTimer::m_szMsg' in a static member function
The solution is to provide a this pointer to the callback function. If you look at the API functions that use callbacks, they always provide a DWORD userValue that will be passed, unmolested, to the callback. With a small change we can generalize this timer object so that any object derived from it will have an OnTimer() function that can do whatever is needed when the timer interval is up.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: |
{{{{ Example 3: Final version, allows access to derived object members }}}}
#include <windows.h>
#include <stdio.h>
#include <Mmsystem.h>
#pragma comment(lib, "Winmm.lib" )
class CBaseTimer {
public:
CBaseTimer(int nIntervalMs=1000) { m_nIntervalMs=nIntervalMs; }; // ctor
~CBaseTimer() { Kill(); }; // dtor
int m_nID;
long m_nIntervalMs;
static void CALLBACK MyTimerProc( UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2 ) {
CBaseTimer* pThis= (CBaseTimer*)dwUser;
pThis->OnTimer();
}
void Start() { // TBD: Check if 0 (failed)
m_nID= timeSetEvent( m_nIntervalMs, 10, MyTimerProc, (DWORD)this, TIME_PERIODIC ); //<<--- Note: this
}
void Kill() {
::timeKillEvent( m_nID );
}
virtual void OnTimer()=0; // must supply a fn in derived objects
};
//------------------------------------------ derived from the base class
class CMsgTickTimer: public CBaseTimer {
public:
CMsgTickTimer( int nIntervalMs, LPCSTR szMsg ) {
m_nIntervalMs= nIntervalMs;
strncpy( m_szMsg, szMsg, sizeof(m_szMsg) );
}
char m_szMsg[100];
void OnTimer() {
printf( "---------- %s ----------- \r\n", m_szMsg );
}
};
//------------------------------------------------ example of usage
int main(int argc, char* argv[])
{
CMsgTickTimer cTimer( 500, "1/2 second is up" );
cTimer.Start();
for (int j=0; j< 40; j++) {
Sleep(100);
printf( "Hi there\r\n" );
}
return 0;
}
|
The output shows that the OnTimer() fn of the derived object is called periodically.
So, what does this have to do with CreateThread, EnumWindows, and the other API functions named above? Just this: The same technique can be used with all of them.
CreateThread( prSecurity, nStackSize, pFn, pParam ... )
ThreadProc( pParam) // will be your this pointer
AfxBeginThread( pFn, param .....)
MyThreadProc( param ) // param will be your this pointer
EnumWindows( pFn, lParam)
EnumWindowsProc( hWnd, lParam ) // lParam will be your this pointer
CreateWindowEx(.... lParam )
WindowProc( hWnd, WM_CREATE, wParam, lParam) // lParam will be your this pointer
LVM_SORTITEMS (message sent to ListView control), WPARAM is the user value
MyCompareFunc( LPARAM p1, LPARAM p2, LPARAM lParamSort); // last one is your this pointer
One other note. You can use the passed-in parameter directly, for instance:
1: 2: 3: 4: 5: 6: |
MyThreadProc( LPVOID p )
{
CSomeObject* pThis= (CSomeObject*)p;
printf("Member string variable is %s", pThis->m_sSomeMember );
}
|
But the technique used in Example 3 is much more useful. It uses pThis to call into a function of the object. That way, execution "gets into" the object and from that point on, your code can access members normally.
1: 2: 3: 4: 5: 6: |
UINT MyObjectThreadProc( LPVOID pParam ) {
MyObject* pThis= (MyObject*)pParam;
UINT nRet= pThis->Run(); // The thread does all the work in here
return( nRet );
}
|
=-=-=-=-=-=-=-=-=-=-=-=-=-
If you liked this article and want to see more from this author, please click the Yes button near the:
Was this article helpful?
label that is just below and to the right of this text. Thanks!
=-=-=-=-=-=-=-=-=-=-=-=-=-

A lot of GUI libraries (including MFC) use the way you explained. This approach allows to use virtual functions and make class hierachies for the GUI controls.
If it's allowed to me, I'd like to say "thanks, good job and nice article."