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

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

问题描述

有C库(我不能改变),它支持

There is C library(which I cannot change), which supports callback function of type

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

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

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

具体来说我有以下问题?

Specifically I have following questions?


  1. extern C

  1. Do I need to declare callback function under "extern C" block?

之后声明回调函数成员函数需要是静态的吗?是否可以使用非静态成员函数?如果是,我该怎么办?并且什么时候推荐使用非静态成员函数?

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

如果函数是模板函数,它是否重要?

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

非类C类型函数比类成员函数有什么优势吗?

Does non-class C type function have any advantages over class member functions?

我在一个旧的VC ++编译器上尝试这些变体,它不支持最新的C ++标准。但代码需要是平台无关的代码,工作在大多数C ++编译器。我想知道回调函数的推荐做法。

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

推荐答案

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

否。 externC只有在直接调用C ++函数时才需要,而不使用C中的函数指针。如果使用函数指针,则不需要externC。

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的非静态成员函数具有对应于该指针的隐式第一参数。

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

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

函数是否是模板函数是否重要?

否,模板函数可以用作回调,只要实例化模板的签名与回调匹配即可。

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

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

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