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