我正在尝试使用类成员作为回调,但是编译器给我以下错误:

Error 2 error C2440: 'type cast' : cannot convert from 'void (__stdcall CWaveIn::* )(HWAVEIN,UINT,DWORD_PTR,DWORD_PTR,DWORD_PTR)' to 'DWORD_PTR'

这样可以将成员函数用作回调吗?以及如何将stdcall成员指针转换为winapi函数请求的DWORD_PTR?
class CWaveIn
{
private:
    void CALLBACK WaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2);
};

void CWaveIn::Open()
{
    (...)
    MMRESULT result = ::waveInOpen(&hWaveIn, currentInputDeviceId, waveFormat, (DWORD_PTR)CWaveIn::WaveInProc, 0, CALLBACK_FUNCTION | WAVE_FORMAT_DIRECT);
}

最佳答案

您不能直接传递类方法。

这是正确的方法:

class CWaveIn
{
private:
    static void CALLBACK staticWaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
    {
        CWaveIn* pThis = reinterpret_cast<CWaveIn*>( dwParam1 );
        pThis->WaveInProc( ... );
    }
    void WaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
    {
       // your code
    }
};

void CWaveIn::Open()
{
     (...)
     MMRESULT result = ::waveInOpen(&hWaveIn, currentInputDeviceId, waveFormat, CWaveIn::staticWaveInProc, this, CALLBACK_FUNCTION | WAVE_FORMAT_DIRECT);
}

10-04 19:39