« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
| 公告 |
|
Blog信息 |
blog名称:FoxWolf 日志总数:127 评论数量:246 留言数量:0 访问次数:854887 建立时间:2006年5月31日 |

| |
[Linux学习]如何用c语言调用c++做成的动态链接库 文章收藏, 软件技术
FoxWolf 发表于 2007/7/17 10:46:29 |
如何用c语言调用c++做成的动态链接库:
链接库头文件:
//head.h
class A
{
public:
A();
virtual ~A();
int gt();
int pt();
private:
int s;
};
.cpp
//firstso.cpp
#include <iostream>
#include "head.h"
A::A(){}
A::~A(){}
int A::gt()
{
s=10;
}
int A::pt()
{
std::cout<<s<<std::endl;
}
编译命令如下:
g++ -shared -o libmy.so firstso.cpp
这时候生成libmy.so文件,将其拷贝到系统库里面:/usr/lib/
进行二次封装:
.cpp
//secso.cpp
#include <iostream>
#include "head.h"
extern "C"
{
int f();
int f()
{
A a;
a.gt();
a.pt();
return 0;
}
}
编译命令:
gcc -shared -o sec.so secso.cpp -L. -lmy
这时候生成第二个.so文件,此时库从一个类变成了一个c的接口.
拷贝到/usr/lib
下面开始调用:
//test.c
#include "stdio.h"
#include "dlfcn.h"
#define SOFILE "sec.so"
int (*f)();
int main()
{
void *dp;
dp=dlopen(SOFILE,RTLD_LAZY);
f=dlsym(dp,"f");
f();
return 0;
}
编译命令如下:
gcc -rdynamic -s -o myapp test.c
运行Z$./myapp
10$ |
|
|