今天在和研发算法讨论时,由于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输出调用结果