C++调用C很方便, 如果C调用C++,主要思想是将C++的动态库封装一层,这一层采用C语言实现,主要封装C++中的类
示例
- test_class.h
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include<iostream>
#include<stdio.h>
class ValueClass
{
private:
int value;
int sum;
public:
ValueClass();
void Add(int i, int j);
};
#endif
- test_class.cpp
#include "test_class.h"
ValueClass::ValueClass(){
printf("hello world \n");
}
void ValueClass::Add(int i, int j){
sum = i+j;
printf("sum : %d value : %d\n",sum,value);
}
- 编程生成动态库
g++ test_class.cpp -shared -o libtestclass.so -I./ -fPIC
封装层
- TestWrapper.h
#ifndef _TEST_WRAPPER_H
#define _TEST_WRAPPER_H
#ifdef __cplusplus
extern "C" {
#endif
void myValueClass(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
- TestWrapper.c
#include "TestWrapper.h"
#include "test_class.h"
#ifdef __cplusplus
extern "C" {
#endif
void myValueClass(int a, int b){
ValueClass t;
t.Add(a,b);
}
#ifdef __cplusplus
};
#endif
- 编译成动态库
g++ TestWrapper.c -shared -o libmyclass.so -L./ -ltestclass -fPIC -Xlinker -rpath=./
主函数
- main.c
#include "TestWrapper.h"
int main()
{
myValueClass(1,2);
}
- 编译
gcc main.c -o main -lmyclass -L./ -I . -Xlinker -rpath=./
该方法比较方便,也有其他方法实现