在某些情况下,需要将C++的接口封装成C函数。
--------------------------------------
首先,我们准备一个C++的so文件,它由以下h和cpp文件生成:
[chengyi@localhost cytest]$ cat cy_test.h
class A
{
public:
A();
virtual ~A();
int gt();
int pt();
private:
int s;
};
[chengyi@localhost cytest]$ cat cy_test_body.cpp
#include <iostream>
#include "cy_test.h"
A::A(){}
A::~A(){}
int A::gt()
{
s=10;
}
int A::pt()
{
std::cout<<s<<std::endl;
}
编译:g++ -shared -o libmy.so cy_test_body.cpp 生成libmy.so文件。
将该so文件cp到/usr/lib下。
------------------------------------
然后,对该接口进行封装:
[chengyi@localhost cytest]$ cat test.cpp
#include <iostream>
#include "cy_test.h"
extern "C"
{
int f();
int f()
{
A a;
a.gt();
a.pt();
return 0;
}
}
编译: gcc -shared -o sec.so test.cpp -lmy 生成sec.so文件,也cp到/usr/lib下。
------------------------------------------
[chengyi@localhost cytest]$ cat test.c
#include <stdio.h>
#include <dlfcn.h>
#define SOFILE "sec.so"
int (*f)();
int main()
{
void *dp;
char * error;
dp=dlopen(SOFILE,RTLD_LAZY);
if (!dp) {
fprintf (stderr, "%s/n", dlerror());
return 1;
}
f=dlsym(dp,"f");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s/n", error);
return 1;
}
f();
return 0;
}
编译: gcc -o test test.c -rdynamic -ldl
这里,由于用到了dlopen等动态加载函数,所以需要-rdynamic -ldl参数。
运行:
[chengyi@localhost cytest]$ ./test
10
本文介绍了如何将C++的接口封装成C函数,通过创建C++的动态链接库(.so文件),并使用C语言调用该库中的函数实现跨语言交互。详细步骤包括编写C++类,生成C++动态库,编写C函数接口,以及在C程序中使用dlopen和dlsym函数动态加载并调用C++接口。
1万+

被折叠的 条评论
为什么被折叠?



