您的位置:首页 > 编程语言 > C语言/C++

extern "C"与C++中的C函数调用(4)—— 如何在C中调用C++函数

2014-04-17 10:43 435 查看
在C++代码里将 C++ 函数声明为extern "C"(由上述分析(2)可知C语言不支持extern "C"声明),然后调用它(在你的 C 或者 C++ 代码里调用)。例如:

//C++代码
#include <iostream>
extern "C" int func(int a,int b);

int func(int a, int b)
{
std::cout << "In the C++" << std::endl;
}


然后,你可以这样使用 func():

//C代码
#include <stdio.h>
int func(int x, int y);

int main()
{
func(3,4);
return 0;
}


当然,这招只适用于非成员函数。如果你想要在 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);
void f_d(double);

void cccc(int i,double d)
{
f_i(i);
f_d(d);
/* ... */
}


注意,这些技巧也适用于在 C 里调用 C++ 类库,即使你不能(或者不想)修改 C++ 头文件。

该翻译的文档Bjarne Stroustrup的原文链接地址是http://www.research.att.com/~bs/bs_faq2.html#callCpp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: