Chinaunix首页 | 论坛 | 博客
  • 博客访问: 67128
  • 博文数量: 43
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-21 21:36
文章分类

全部博文(43)

文章存档

2009年(3)

2008年(40)

我的朋友

分类: C/C++

2008-12-11 15:51:26

在Linux中可以动态加载库,其使用方法如下:
1. 先生成一个动态库libtest.so
/* test.c */
#include
#include
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
#include
#include
#include
#include /* 必须加这个头文件 */
#include

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的结果
阅读(590) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~