C中如何调⽤C++函数、类内函数
在C中如何调⽤C++函数的问题,简单回答是将函数⽤extern "C"声明,当被问及如何将类内成员函数声明时,⼀时语塞,后来⽹上查了下,⽹上有⼀翻译C++之⽗的⽂章可以作为解答,遂拿来Mark⼀下。
将C++函数声明为``extern "C"''(在你的C++代码⾥做这个声明),然后调⽤它(在你的C或者C++代码⾥调⽤)。例如:
// C++ code:
extern "C" void f(int);
void f(int i)
{
// ...
}
然后,你可以这样使⽤f():
/* C code: */
void f(int);
void cc(int i)
{
f(i);
/* ... */
}
当然,这招只适⽤于⾮成员函数。如果你想要在C⾥调⽤成员函数(包括虚函数),则需要提供⼀个简单的包装(wrapper)。例如:
// C++ code:
class C
{
// ...
virtual double f(int);
};
extern "C" double call_C_f(C* p, int i) // wrapper function
{
return p->f(i);
}
然后,你就可以这样调⽤C::f():
/* C code: */
double call_C_f(struct C* p, int i);
void ccc(struct C* p, int i)
{
double d = call_C_f(p,i);
/* ... */
}
如果你想在C⾥调⽤重载函数,则必须提供不同名字的包装,这样才能被C代码调⽤。例如:// C++ code:
void f(int);
void f(double);
extern "C" void f_i(int i) { f(i); }
extern "C" void f_d(double d) { f(d); }
然后,你可以这样使⽤每个重载的f():
/* C code: */
void f_i(int);