C++ Callback function

2019-08-02 09:46发布

I'm setting a timer using afxwin SetTimer function. This function receives three params one of which is a callback function.

I set a callback function in a class (let's call it NS) and tried to pass it as an argument. However the compiler complains that this:

void (__stdcall NS::*) (HWND, UINT, UINT_PTR, DWORD);

is not the same as:

void (__stdcall *) (HWND, UINT, UINT_PTR, DWORD);

What should I do?

1条回答
【Aperson】
2楼-- · 2019-08-02 10:13

Make the function static*. Otherwise it's not even a function, but rather a member function, which is a very different animal. Moreover, it doesn't otherwise make sense to "pass the function in a class as a callback", as you put it: A non-static member function is tied to the state of an object instance of that class.

(Also, search this site, this question has been asked a million times over and there are many good alternatives spread out throughout SO.)

*) As @James points out, this is not sufficient if the callback function has a C interface, in which case you also need a free extern "C" wrapper function.

查看更多
登录 后发表回答