這種需求應該就沒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函數