C语言调用C++非静态成员函数

我手上有个C的库函数,有一个函数需要使用回调函数
我编写一个父类,内部有成员函数,就是需要被C用于回调的函数
之后我的很多类都是继承,该父类,所以不能写成静态成员函数
我要把C++的非静态成员函数传给C函数作为回调函数该怎么写
extern "C"{
#include <stdio.h>
void CFun(CB);
void CPrint(int);
}
void CPrint(int n){
printf("%d\n",n);
}
void CFun(CB f){
f(5);
}
class CallCPPFunc{
public:
typedef void (CallCPPFunc::*PPFunc)(int);
void CPPPrint(int n){printf("%d\n",n);}
};
int main(void){
CFun(CPrint); //输出5
void (CallCPPFunc::*ccbb)(int)=&CallCPPFunc::CPPPrint;
std::cout<<"ccbb:"<<ccbb<<std::endl;
CallCPPFunc call;
(call.*ccbb)(10); //输出10
//CFun(call.CPPPrint); //类型不匹配
//CFun((call.*ccbb));//非静态
std::cout<<"hello world!";
}

定义一个父类的对象,通过父类对象调用其成员函数就行了追问

我试过两种:

    使用对象,在C函数里放入成员函数.error:argument of type `void (CallCPPFunc::)(int)' does not match `void (*)(int)'

    使用对象,内部再封装类指针,传递给C.error:error: invalid use of non-static member function

追答

如果那个C函数是子类的成员函数,通过继承父类继承回调函数。不是的话回调函数不要在类里面声明

追问

C函数是C语言库里的函数,非C++语言的
这是混编...所以我的C函数使用了extern "C"{}
先不说回调函数,这其实只是C++对象的普通成员函数.
纯C函数需要调用对象的普通成员函数作为纯C函数的回调函数

追答

成员函数只能通过对象调用,不能通过地址引用,我没办法了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-07-11
这种方法试一下

class CallCPPFunc{
public:
typedef void (CallCPPFunc::*PPFunc)(int);
static void CPPPrint(void* c,int n){
static_cast <CallCPPFunc*>(c)->CPPPrint(n);
}
void CPPPrint(int n){printf("%d\n",n);}
};追问

这样调用对象成员函数没问题的..可以用的.
但跟问题并没有什么关系

追答

你不就是为了对象成员能够被C函数调用么

第2个回答  2016-07-11
没法,非成员函数的地址又获取不到追问

是非静态成员函数,也是成员函数啊.如果在有对象就有地址了.
这个函数我也是在对象构造后,才放入成员函数的地址作为C的回调.

相似回答