这种需求应该就没C++程序调用C函数需求多了.目前的实现基本只有一类方法,即通过处理被调用的C++文件.
文 中给出的仍然是完整的,具体的,但又最基本最简单的实现,至于理论性的东西在网上很容易搜索的到.这里是针对调用C++的成员函数的实现.
aa.h
class AA {
int i;
public:
int ThisIsTest(int a, int b);
float ThisIsTest(float a, float b);
};
extern "C" int ThisIsTest_C(void* s, int a,int b);
extern "C" float PolymorphicTest_C(void* s,float a, float b);
aa.cpp:
#include "aa.h"
int AA::ThisIsTest(int a, int b){
return (a + b);
}
float AA::PolymorphicTest(float a, float b){
return (a+b);
}
int ThisIsTest_C(void* s, int a,int b){
AA* p = (AA*)s;
return p->ThisIsTest(a,b);
}
float PolymorphicTest_C(void* s,float a, float b){
AA* p = (AA*)s;
return p->ThisIsTest(a,b);
}
a.h:
#ifndef __A_H
#define __A_H
int bar(void* s,int a, int b);
int bar_float(void* s,float a, float b);
#endif
a.c
#include <stdio.h>
#include "a.h"
extern int ThisIsTest_C(void* s, int a,int b);
extern float PolymorphicTest_C(void* s,float a, float b);
int bar(void* s,int a, int b) {
printf("result=%d/n", ThisIsTest_C(s,a, b));
return 0;
}
int bar_float(void* s,float a, float b) {
printf("result=%f/n", PolymorphicTest_C(s,a, b));
return 0;
}
main.c:
#include "a.h"
struct S {
int i;
};
struct S s;
int main(int argc, char **argv){
int a = 1;
int b = 2;
float c = 1.5;
float d = 1.4;
bar((void*)&s,a, b);
bar_float((void*)&s,c,d);
return(0);
}
Makefile:
all:
gcc -Wall -c a.c -o a.o
gcc -Wall -c aa.cpp -o aa.o
gcc -Wall -c main.c -o main.o
g++ -o test *.o
因为C++兼容C,所以C++也有外部函数,C调用C++外部函数很简单.
调用成员函数时,我们只有函数int ThisIsTest(int a, int b)和float ThisIsTest(float a, float b)
extern "C" int ThisIsTest_C(void* s, int a,int b)和extern "C" float PolymorphicTest_C(void* s,float a, float b)是为了调用
上面函数而不得不封装的.
如果类AA有外部函数int function(int a,int b),则我们只需要在C++头文件此函数名前加上extern "C"即可.调用方法一样.这种情况下,我们不需要定义跟AA类相同的struct S.
总结如下:
被调用C++外部函数要使用extern "C"声明,或封装成员函数为外部函数后加extern "C"声明.
多个重载函数封装外部函数函数名必须不同.
被调用的函数参数列表中不能使用类和引用及其他C代码没办法处理的东西.
如果被调用函数所在类有全局变量或静态变量等,我们就必须构造相应的C++类而非C结构体,这时,main()函数要用C++编译器来编译.
如果非要在C中实现main函数,那可以在C++中定义main_c函数