C语言调用C++库接口的方法概述

最近需要在由纯c语言编写的代码中调用C++的动态库,在网上找了一些资料,现在总结下解决方法。

主要的思想就是将C++的动态库再封装一层,在这一层编写C语言的函数api,这API中使用C++动态库提供的类;

具体例子如下:

1,假如C++动态库包含如下代码:
//myclass.h

#ifndef _MYCLASS_H
#define _MYCLASS_H
class MyClass
{
    public:
        void print();
};
#endif

//myclass.cc

#include <iostream>
#include "myclass.h"
using namespace std;
 
void
MyClass::print()
{
    cout << "MyClass::print() called" << endl;
}

编译链接生成动态库:libmyclass.so
g++ myclass.cc -shared -o libmyclass.so -I./ -fPIC

2,封装libmyclass.so中类的接口,生成libmyfunc.so
//myfunc.h

#ifndef _MYFUNCTION_H
#define _MYFUNCTION_H
 
#ifdef _cplusplus
extern "C" {
#endif
    void myprint();
#ifdef _cplusplus
}
#endif
#endif

//myfunc.c

#include "myclass.h"
#ifndef _cplusplus
#define _cplusplus
#include "myfunc.h"
#endif
void
myprint()
{
    MyClass mc;
    mc.print();
}

编译链接生成动态库(C语言接口):
g++ myfunc.c -shared -o libmyfunc.so -L./ -lmyclass -fPIC -Xlinker -rpath=./
3,测试libmyfunc.so中提供的接口
//main.c

#include "myfunc.h"
int 
main(int argc, char **argv)
{
    myprint(); 
}

编译链接生成可执行代码:
gcc main.c -o main -lmyfunc -L./ -I. -Xlinker -rpath=./
执行main文件,输出如下:
MyClass::print() called
ok,大功搞成!!
注意事项:
1,注意myfunc.so必须是用g++来生成的,如果使用gcc,会不识别其中的类(这个解释不一定正确)
2,注意myfunc.h中_cpluscplus的用法,因为myfunc.h被main.c和myfunc.c两个文件用到,而extern仅被g++能够识别,
而不能够被gcc识别,解释的不一定对,还没有想清楚。。。。。
本文地址:http://www.yaronspace.cn/blog/index.php/archives/1046

来自 yaronspace.cn   本文链接: http://yaronspace.cn/blog/archives/1046  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值