extern "C"与C++中的C函数调用(4)—— 如何在C中调用C++函数
2014-04-17 10:43
435 查看
在C++代码里将 C++ 函数声明为extern "C"(由上述分析(2)可知C语言不支持extern "C"声明),然后调用它(在你的 C 或者 C++ 代码里调用)。例如:
然后,你可以这样使用 func():
当然,这招只适用于非成员函数。如果你想要在 C 里调用成员函数(包括虚函数),则需要提供一个简单的包装(wrapper)。例如:
然后,你就可以这样调用 C::f():
如果你想在 C 里调用重载函数,则必须提供不同名字的包装,这样才能被 C 代码调用。例如:
然后,你可以这样使用每个重载的 f():
注意,这些技巧也适用于在 C 里调用 C++ 类库,即使你不能(或者不想)修改 C++ 头文件。
该翻译的文档Bjarne Stroustrup的原文链接地址是http://www.research.att.com/~bs/bs_faq2.html#callCpp
//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
相关文章推荐
- extern "C"与C++中的C函数调用(3)—— 如何在C++中调用C函数
- 为什么在C++里调用被C编译器编译的函数,要加extern "c"
- C++调用C函数,为什么要加extern "C"?
- 【c++面试题】c++中函数的重载,c++程序中调用C编译器编译后的函数为什么要加extern "C 4000 "
- extern "C"与C++中的C函数调用(1)
- C++调用C函数与Extern "C"
- 如果 C++程序要调用已经被编译后的C 函数,该怎么办?extern "C"
- Why? 在C++中调用被C编译后的函数,要在声明的前面加extern "C"
- C++函数重载实现的原理以及为什么在C++中调用C语言编译的函数时要加上extern "C"声明
- extern "C" c++如何实现函数的重载
- 用C调用C++函数来看extern "C"的作用
- C++ 文件里面调用C文件里面的函数——extern "C" 用法解析
- Why? 在C++中调用被C编译后的函数,要在声明的前面加extern &quot;C&quot;
- extern "C"与C++中的C函数调用(2)
- C++调用被C编译器编译过的函数要加extern "C"(转自http://zhidao.baidu.com/question/193713666.html)
- C/C++中函数的调用约定(__cdecl, __stdcall)以及extern, extern “C"的详细解释
- 在C++中调用被C编译器编译后的函数,为什么要加extern "C"
- extern "C"/C中如何调用C++
- C++调用C函数,为什么要加extern "C"?
- c++程序调用被C编译器编译后的函数为什么要加extern "C"