使用 C++ 类成员函数作为 C 回调函数
我有一个 C 库,需要注册一个回调函数来自定义一些处理.回调函数类型为int a(int *, int *)
.
I have a C library that needs a callback function to be registered to customize some processing. Type of the callback function is int a(int *, int *)
.
我正在编写类似于以下的 C++ 代码,并尝试注册一个 C++ 类函数作为回调函数:
I am writing C++ code similar to the following and try to register a C++ class function as the callback function:
class A {
public:
A();
~A();
int e(int *k, int *j);
};
A::A()
{
register_with_library(e)
}
int
A::e(int *k, int *e)
{
return 0;
}
A::~A()
{
}
编译器抛出以下错误:
In constructor 'A::A()',
error:
argument of type ‘int (A::)(int*, int*)’ does not match ‘int (*)(int*, int*)’.
我的问题:
- 首先,是否可以像我尝试的那样注册 C++ 类成员函数,如果可以,如何注册?(我在 http://www.parashift 阅读了 32.8.com/c++-faq-lite/mixing-c-and-cpp.html.但在我看来它并没有解决问题)
- 是否有替代/更好的方法来解决这个问题?
- First of all is it possible to register a C++ class memeber function like I am trying to do and if so how? (I read 32.8 at http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html. But in my opinion it does not solve the problem)
- Is there a alternate/better way to tackle this?
推荐答案
如果成员函数是静态的,你可以这样做.
You can do that if the member function is static.
A 类的非静态成员函数有一个 class A*
类型的隐式第一个参数,它对应于 this 指针.这就是为什么你只能在回调的签名也有 class A*
类型的第一个参数时注册它们.
Non-static member functions of class A have an implicit first parameter of type class A*
which corresponds to this pointer. That's why you could only register them if the signature of the callback also had the first parameter of class A*
type.
相关文章