如何使用 C++ 成员函数作为 C 框架的回调函数 [英] How to use a C++ member function as the callback function for a C framework

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

问题描述

有一个支持类型回调函数的 C 库(我无法更改)

There is a C library (which I cannot change) that supports a callback function of the type

void (*callback)(void *appContext, int eventid)

我想设置一个 C++ 函数作为回调.

I want to set a C++ function as the callback.

具体来说我有以下问题?

Specifically I have following questions?

  1. 是否需要在"extern C"块下声明回调函数?

成员函数是否需要是静态的才能成为回调函数?是否可以使用非静态成员函数?如果是,如何?什么时候推荐使用非静态成员函数?

Does a member function need to be static to be the callback function? Is it possible to use a non-static member function? If yes, how? And when is it recommended to use a non-static member function?

函数是否是模板函数有关系吗?

Does it matter if the function is a template function or not?

非类 C 风格的函数与类成员函数相比有什么优势吗?

Does a non-class C style function have any advantages over a class member function?

我正在旧的 VC++ 编译器上尝试这些变体,该编译器不支持最新的 C++ 标准.但是代码需要独立于平台,并且应该适用于大多数 C++ 编译器.我想知道回调的推荐做法是什么?

I am trying these variants on a old VC++ compiler, which does not support the latest C++ standard. But the code needs to be platform independent and should work on most C++ compilers. I want to know what is recommended practice with callbacks?

推荐答案

回调函数需要在extern "C"下声明吗?

没有.仅当您从 C 直接调用 C++ 函数而不使用函数指针时,才需要 extern "C".如果使用函数指针,则不需要 extern "C".

NO. extern "C" is necessary only when you are calling a C++ function directly, without the use of function pointers, from C. If function pointers are used, extern "C" is not required.

我可以使用非静态成员函数作为回调吗?

没有.类 A 的非静态成员函数有一个隐式的第一个参数对应于 this 指针.

NO. Non-static member functions of class A have an implicit first parameter corresponding to this pointer.

我可以使用静态成员函数作为回调吗?

是的,只要签名与回调的签名匹配即可.

YES, as long as signature matches with that of the callback.

函数是否是模板函数有关系吗?

NO,只要实例化模板的签名与回调匹配,模板函数就可以用作回调.

NO, template function can be used as callbacks as long as the signature of the instantiated template matches with the callback.

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

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