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++能够识别,


【同理 可以使用 ar rcs  libmyclass.a  my.o 编译 静态库】

-------静态库 在编译的时候 会出现 delete ,new, operator 等操作符没有定义  需要在gcc 时候加入-lstdc++ 链接上c++基础库  。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiny丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值