C ++回调函数 [英] C++ Callback function

查看:248
本文介绍了C ++回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用afxwin SetTimer函数设置计时器。这个函数接收三个参数,其中一个是回调函数。

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

我在一个类中设置了一个回调函数(我们称之为NS),并试图将它作为参数。然而,编译器抱怨这:

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);

与以下不同:

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

我该怎么办?

推荐答案

使函数 static *。否则它甚至不是一个函数,而是一个成员函数,这是一个非常不同的动物。此外,将作为回调在类中传递函数没有其他意义,如下所示:非静态成员函数绑定到对象实例的状态该类。

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.

(此外,搜索此网站,此问题已被问过百万次,有很多好的替代品遍布整个SO。)

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

*)正如@James指出的,如果回调函数有一个C接口,这是不够的,在这种情况下,你还需要一个免费的 extern C包装函数。

*) 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.

这篇关于C ++回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆