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

在C++代码里将 C++ 函数声明为extern "C"(由上述分析(2)可知C语言不支持extern "C"声明),而后调用它(在你的 C 或者 C++ 代码里调用)。例如:html

//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():ios

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

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

固然,这招只适用于非成员函数。若是你想要在 C 里调用成员函数(包括虚函数),则须要提供一个简单的包装(wrapper)。例如:app

// 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 代码调用。例如:spa

// 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++ 头文件。code

该翻译的文档Bjarne Stroustrup的原文连接地址是http://www.research.att.com/~bs/bs_faq2.html#callCpphtm

相关文章
相关标签/搜索