Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1680877
  • 博文数量: 1493
  • 博客积分: 38
  • 博客等级: 民兵
  • 技术积分: 5834
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 17:28
文章分类

全部博文(1493)

文章存档

2016年(11)

2015年(38)

2014年(137)

2013年(253)

2012年(1054)

2011年(1)

分类:

2012-08-06 17:25:58

原文地址:linux c调用自己写的c++库 作者:zzappled

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

aa.cpp

#include "aa.h"

int sample::method()

{

    cout<<"method is called!\n";

}

aa.h

#include

#include

using namespace std;

class sample

{

    public:

    int method();

};

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

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

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

mylib.cpp

#include "aa.h"

#ifndef _cplusplus

#define _cplusplus

#include "mylib.h"

#endif

int myfunc()

{

    sample ss;

    ss.method();

    return 0;

}

mylib.h

#ifdef _cplusplus

extern "C"

{

    #endif

    int myfunc();

    #ifdef _cplusplus

}

#endif

在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

 

main.c

#include

#include

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

阅读(203) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~