C语言调用C++的动态库

C语言中没有类的概念,如何调用呢,需要封装一下,增加一个中间层。这个中间层屏蔽了类,提供一个函数给上层,并且还要用c++编译器来编译。

封装策略:

1. C++代码如下:

myclass.h

#ifndef _MYCLASS_H
#define _MYCLASS_H

class MyClass
{
    public:
        void print();
};

#endif
myclass.cpp

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

将上面的两个文件生成动态库libmyclass.so,编译命令如下:

g++ myclass.cpp -shared -o libmyclass.so -I./ -fPIC

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

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();
}

编译命令如下

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=./

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值