7

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

    ...
}
4

1 に答える 1

9

メンバー関数と 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

于 2011-06-24T19:45:16.473 に答える