C调用C++函数库

C调用C++函数库,通常不能直接调用,须要将C++库转换成C接口输出,方能够使用C调用,看下面的例子:  linux

  
  
  
  
  
aa.h #include <iostream> #include <string> using namespace std; class sample { public: int method(); };

  
  
  
  
  
aa.cpp #include "aa.h" int sample::method() { cout<<"method is called!\n"; }


将上面的两个文件生成动态库libaa.so放到 /usr/lib目录下,编译命令以下  ios

  
  
  
  
  
g++ -fpic -shared -o /usr/lib/libaa.so aa.cpp -I ./

因为在C中不能识别类,因此要将上面类的成员函数封装成C接口函数输出,下面进行封装,将输出接口转换成C接口。  函数

  
  
  
  
  
mylib.h #ifdef _cplusplus extern "C" { #endif int myfunc(); #ifdef _cplusplus } #endif
   
   
   
   
   
mylib.cpp #include "aa.h" #ifndef _cplusplus #define _cplusplus #include "mylib.h" #endif int myfunc() { sample ss; ss.method(); return 0; }


在linux下,gcc编译器并没用变量_cplusplus来区分是C代码仍是C++代码,若是使用gcc编译器,这里咱们能够本身定义一个变量_cplusplus用于区分C和C++代码,因此在mylib.cxx中定义了一个变量_cplusplus用于识别是否须要“extern "C"”将函数接口封装成C接口。可是若是使用g++编译器则不须要专门定义_cplusplus,编译命令以下:  spa

gcc -shared -o mylib.so mylib.cpp -L. -laa  code

  
  
  
  
  
main.c #include <stdio.h>#include <dlfcn.h>int main(void) { int (*dlfunc)(); void *handle; //定义一个句柄 handle = dlopen("./mylib.so", RTLD_LAZY);//得到库句柄 dlfunc = dlsym(handle, "myfunc"); //得到函数入口 (*dlfunc)(); dlclose(handle); return 0; }

编译命令以下:  接口

gcc -o main main.c ./mylib.so -ldl get

 



相关文章
相关标签/搜索