Using a C++ class member function as a C callback function(使用 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.
这篇关于使用 C++ 类成员函数作为 C 回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C++ 类成员函数作为 C 回调函数


- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07