织梦CMS - 轻松建站从此开始!

罗索

Linux C调用C++库

落鹤生 发布于 2011-10-28 09:45 点击:次 
C调用C++函数库,一般不能直接调用,需要将C++库转换成C接口输出,方可以使用C调用
TAG:

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

  • aa.cxx

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

  • aa.h

#include <iostream>

using namespace std;
class sample
{
    public:
    int method();
};

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

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

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

  • mylib.cxx

#include "add.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,编译命令如下:

      g++ -fpic -shared -g -o mylib.so mylib.cxx -la -I ./

  • main.c

#include <stdio.h>
#include <dlfcn.h>
#include "mylib.h"

int
main()
{
    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

下面就可以执行了。

需要说明的是,由于main.c 和 mylib.cxx都需要包含mylib.h,并且要将函数myfunc封装成C接口函数输出需要“extern "C"”,而C又不识别“extern "C"”,所以需要定义_cplusplus来区别处理mylib.h中的函数myfunc。

在main.c的main函数中直接调用myfunc()函数也能执行,这里介绍的是常规调用库函数的方法。

(tzc)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201110/15228.html]
本文出处:tzc.is-programmer.com 作者:tzc
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容