linux 中的动态库加载

在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(编译时要使用共享库dl 其中有dlopen dlsynm dlerror dlclose 函数)
运行main,将会看到调用test1,和test2的结果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值