使用C ++类成员函数作为C回调函数我有一个C库,需要注册回调函数来定制一些处理。回调函数的类型是int a(int *, int *)。我正在编写类似于以下内容的C ++代码,并尝试将C ++类函数注册为回调函数:class A {
public:
A();
~A();
int e(int *k, int *j);};A::A(){
register_with_library(e)}intA::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 ++类的memeber函数,就像我想要做的那样,如果是这样的话怎么样?(我在http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html上阅读了32.8 。但在我看来它并没有解决问题)是否有替代/更好的方法来解决这个问题?
3 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
如果成员函数是静态的,则可以这样做。
类A的非静态成员函数具有隐式的第一个类型参数,class A*该参数对应于该指针。这就是为什么如果回调的签名也有第一个class A*类型的参数,你只能注册它们。
缥缈止盈
TA贡献2041条经验 获得超4个赞
如果成员函数不是静态的,你也可以这样做,但它需要更多的工作(参见将C ++函数指针转换为c函数指针):
#include <stdio.h>#include <functional>template <typename T>struct Callback;template <typename Ret, typename... Params>struct Callback<Ret(Params...)> {
template <typename... Args>
static Ret callback(Args... args) {
func(args...);
}
static std::function<Ret(Params...)> func; };template <typename Ret, typename... Params>std::function<Ret(Params...)> Callback<Ret(Params...)>::func;void register_with_library(int (*func)(int *k, int *e)) {
int x = 0, y = 1;
int o = func(&x, &y);
printf("Value: %i\n", o);}class A {
public:
A();
~A();
int e(int *k, int *j);};typedef int (*callback_t)(int*,int*);A::A() {
Callback<int(int*,int*)>::func = std::bind(&A::e, this, std::placeholders::_1, std::placeholders::_2);
callback_t func = static_cast<callback_t>(Callback<int(int*,int*)>::callback);
register_with_library(func); }int A::e(int *k, int *j) {
return *k - *j;}A::~A() { }int main() {
A a;}这个例子在它编译的意义上是完整的:
g++ test.cpp -std=c++11 -o test
你需要c++11国旗。在您看到的代码中,register_with_library(func)调用func了动态绑定到成员函数的静态函数e。
- 3 回答
- 0 关注
- 1603 浏览
添加回答
举报
0/150
提交
取消
