【发布时间】:2011-09-22 07:27:23
【问题描述】:
如何将成员函数指针转换为TIMERPROC 类型以用于WINAPI SetTimer?下面的代码 sn-p 显示了我现在是如何做的,但是当我编译时出现此错误:
错误 C2664: 'SetTimer' : 无法将参数 4 从 'void (__stdcall CBuildAndSend::* )(HWND,UINT,UINT_PTR,DWORD)' 转换为 'TIMERPROC'
回调需要绑定到它的原始类实例。如果有更好的方法来做到这一点,我会全力以赴。谢谢。
class CMyClass
{
public:
void (CALLBACK CBuildAndSend::*TimerCbfn)( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime );
private:
void CALLBACK TimeoutTimerProc( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime );
};
CMyClass::CMyClass()
{
...
this->TimerCbfn = &CBuildAndSend::TimeoutTimerProc;
...
::CreateThread(
NULL, // no security attributes
0, // use default initial stack size
reinterpret_cast<LPTHREAD_START_ROUTINE>(BasThreadFn), // function to execute in new thread
this, // thread parameters
0, // use default creation settings
NULL // thread ID is not needed
)
}
void CALLBACK CMyClass::TimeoutTimerProc( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
...
}
static DWORD MyThreadFn( LPVOID pParam )
{
CMyClass * pMyClass = (CMyClass *)pParam;
...
::SetTimer( NULL, 0, BAS_DEFAULT_TIMEOUT, pMyClass->TimerCbfn ); // <-- Error Here
...
}
【问题讨论】:
-
顺便说一句,每当您在 win32 API 中使用函数(或函数指针)进行强制转换时,通常都表明存在某种错误。如果它没有按原样编译,那么通常需要更改函数;添加演员只是在掩盖问题。幸运的是,C++(指向)成员函数与(指向)普通函数完全不同,因此在这种情况下甚至 reinterpret_cast 都不可能。
标签: c++ winapi casting member-function-pointers