【genius_platform软件平台开发】第六点:C语言和C++相互调用

今天在和研发算法讨论时,由于MNN推理库是C++编写的,而我们研发算法使用C语言写的,嵌入式应用也是C语言,所以就需要把MNN库的类接口在使用之前进行一层C接口封装

直接看例子,涉及到其他的可以使用类成员函数指针等方式

C++  cpp.h文件

/*
 * 定义的C++应用类
 */

#ifndef __C_H__
#define __C_H__

// 定义C++类
class CPP
{
public:
    // 声明成员函数
    void set(int n);

private:
    // 定义数据成员
    int m_n;
};
#endif

C++  cpp.cpp文件

/*
 * C++类的实现
 */

#include "cpp.h"
#include "stdio.h"

void CPP::set(int n)
{
    m_n = n;
    // 打印log
    printf("调用C++类成员函数成功:m_n=%d\n",n);
}

C++  wrapper.h文件

/*
 * C语言中间0
 */
#ifndef __WRAPPER_H_
#define __WRAPPER_H_

#ifdef __cplusplus
extern "C" {
#endif

    void setN(int handle, int n);

#ifdef __cplusplus
};
#endif

#endif

C++  wrapper.cpp文件

/*
 *C语言中间件从cpp
 */
#include "wrapper.h"
#include "cpp.h"
#include <vector>
using namespace std;

#ifdef _cplusplus
extern "c"
{
#endif

int g_handle = 0;
vector<void*> g_vt;

void setN(int handle, int n)
{
    // 创建C++对象,调用obj成员函数
    CPP* pc = new CPP();
    if(pc)
    {
        pc->set(1);        
    }
}
#ifdef _cplusplus
};
#endif

test.c 测试程序

#include "wrapper.h"

int main()
{
    
    // 调用C接口
    setN(1, 2);

    return 0;
}

执行过程和结果

1. 执行 g++编译cpp文件,g++ -c cpp.cpp wrapper.cpp 生成.o文件

2. 执行gcc编译c文件,gcc test.c -o test wrapper.o cpp.o -lstdc++生成可执行文件test

3. 执行./test输出调用结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

隨意的風

如果你觉得有帮助,期待你的打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值