[英]Converting Member Function Pointer to TIMERPROC
如何將成員函數指針轉換為TIMERPROC
類型以與WINAPI SetTimer
? 下面的代碼片段顯示了我現在是如何做的,但是當我編譯時,我收到此錯誤:
錯誤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
...
}
成員函數和TIMEPROC不兼容類型。
您需要使成員函數static
。 然后它將工作,假設參數列表在靜態成員函數和TIMEPROC中都相同。
class CMyClass
{
public:
//modified
void (CALLBACK *TimerCbfn)(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
private:
//modified
static void CALLBACK TimeoutTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime );
};
函數指針和成員函數都被修改。 現在它應該工作。
現在,由於回調函數變為靜態,因此它無法訪問類的非靜態成員,因為函數中沒有this
指針。
要訪問非靜態成員,您可以執行以下操作:
class CMyClass
{
public:
static void CALLBACK TimerProc( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime );
//add this static member
static std::map<UINT_PTR, CMyClass*> m_CMyClassMap; //declaration
};
//this should go in the CMyClass.cpp file
std::map<UINT_PTR, CMyClass*> CMyClass::m_CMyClassMap; //definition
static DWORD MyThreadFn( LPVOID pParam )
{
CMyClass * pMyClass = (CMyClass *)pParam;
UINT_PTR id = ::SetTimer( NULL, 0, BAS_DEFAULT_TIMEOUT, CMyClass::TimerProc);
//store the class instance with the id as key!
m_CMyClassMap[id]= pMyClass;
}
void CALLBACK CMyClass::TimerProc( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
//retrieve the class instance
CMyClass *pMyClass= m_CMyClassMap[idEvent];
/*
now using pMyClass, you can access the non-static
members of the class. e.g
pMyClass->NonStaticMemberFunction();
*/
}
我從我的實現中刪除了TimerCbfn
,因為它並不真正需要。 您可以將TimerProc
直接傳遞給SetTimer
作為最后一個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.