有问题?Q我吧,Always Online!

C调用C++函数库

C调用C++函数库,一般不能直接调用,需要将C++库转换成C接口输出,方可以使用C调用,看下面的例子: 

  1. aa.h
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. class sample
  6. {
  7. public:
  8. int method();
  9. };

  1. aa.cpp
  2. #include "aa.h"
  3. int sample::method()
  4. {
  5. cout<<"method is called!\n";
  6. }


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

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

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

  1. mylib.h
  2. #ifdef _cplusplus
  3. extern "C"
  4. {
  5. #endif
  6. int myfunc();
  7. #ifdef _cplusplus
  8. }
  9. #endif
  1. mylib.cpp
  2. #include "aa.h"
  3. #ifndef _cplusplus
  4. #define _cplusplus
  5. #include "mylib.h"
  6. #endif
  7. int myfunc()
  8. {
  9. sample ss;
  10. ss.method();
  11. return 0;
  12. }


在linux下,gcc编译器并没用变量_cplusplus来区分是C代码还是C++代码,如果使用gcc编译器,这里我们可以自己定义一个变量_cplusplus用于区分C和C++代码,所以在mylib.cxx中定义了一个变量_cplusplus用于识别是否需要“extern "C"”将函数接口封装成C接口。但是如果使用g++编译器则不需要专门定义_cplusplus,编译命令如下: 

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

  1. main.c
  2. #include <stdio.h>
  3. #include <dlfcn.h>
  4. int main(void)
  5. {
  6. int (*dlfunc)();
  7. void *handle; //定义一个句柄
  8. handle = dlopen("./mylib.so", RTLD_LAZY);//获得库句柄
  9. dlfunc = dlsym(handle, "myfunc"); //获得函数入口
  10. (*dlfunc)();
  11. dlclose(handle);
  12. return 0;
  13. }

编译命令如下: 

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

 





posted @ 2014-08-20 16:33  嵌入式博客园  阅读(1939)  评论(0编辑  收藏  举报