【linux 开发】Linux 加载使用动态库实例
来源:互联网 发布:asp 防sql注入 编辑:程序博客网 时间:2024/05/19 23:59
动态加载库
在Linux中可以动态加载库,其使用方法如下:
1. 先生成一个动态库libtest.so
/* test.c */
#include <stdio.h>
#include <stdio.h>
void test1(int no)
{
printf("*****************************************\n");
printf("This is test1, the number is %d.\n", no);
printf("*****************************************\n");
}
void test2(char *str)
{
printf("=========================================\n");
printf("This is test2, the string is %s.\n", str);
printf("=========================================\n");
}
编译库:
gcc -fPIC -shared -o libtest.so test.c
这样就可以生成libtest.so动态库。
在这个库里,定义个两个函数test1,test2,下面将在程序中加载libtest.so,然后调用test1,test2。
2. 动态加载libtest.so
/* main.c */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dlfcn.h> /* 必须加这个头文件 */
#include <assert.h>
int main()
{
void *handler = dlopen("libtest.so", RTLD_NOW);
assert(handler != NULL);
void (*test1)(int) = dlsym(handler, "test1");
assert(test1 != NULL);
void (*test2)(char *) = dlsym(handler, "test2");
assert(test2 != NULL);
(*test1)(10);
(*test2)("hello");
dlclose(handler);
return 0;
}
/* end */
在这个程序中,dlopen函数用来打开一个动态库,其返回一个void *的指针,如果失败,返回NULL。
dlsym返回一个动态库中的一个函数指针,如果失败,返回NULL。
dlclose关闭指向动态库的指针。
编译的时候需要加上 -ldl
gcc -o main main.c -ldl
运行main,将会看到调用test1,和test2的结果。
- 【linux 开发】Linux 加载使用动态库实例
- Linux 动态库动态加载实例
- Linux下动态加载库的实例
- linux 动态链接库加载实例
- 【linux 开发】多个动态库加载使用注意事项
- linux c/c++ 动态库开发实例
- pkgconfig工具使用 linux动态库加载
- linux 动态加载动态库
- linux 动态加载动态库
- linux 动态加载动态库
- linux 动态链接库加载
- linux共享库动态加载
- linux 中的动态库加载
- Linux下动态加载库
- linux 动态链接库加载
- linux 中的动态库加载
- Linux动态加载库剖析
- linux中加载动态库
- 《Android的设计与实现:卷I》重印版
- 设置Derby做为Linux自启动服务方式运行
- 词根词缀联想记忆法
- 再次回来
- 一张图让你读懂开源协议
- 【linux 开发】Linux 加载使用动态库实例
- 来这里好久...
- 极大极小树的剪枝算法1 alpha-beta剪枝
- uva10167
- HDoj Integer Inquiry(大数)
- 黑马程序员-传智播客SQL题
- IOS 上传代码审核
- Delete,Update连表(left join)删除
- 也谈测试核心竞争力