cat dlopen.c
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char *argv)
{
int index = -1;
void *handle;
int (*get_index)(int);
int ret = -1;
// 获取handle
handle = dlopen("./liba.so", RTLD_NOW);
if (handle == NULL) {
printf("dlopen error!:%s\n", dlerror());
return -1;
}
//获取函数,get_card_index为so中的实现函数,get_index指向该函数;
get_index = dlsym(handle, "get_card_index");
if (get_index == NULL) {
printf("dlsym error!\n");
dlclose(handle);
return -1;
}
ret = get_index(index);
printf("ret:%d\n", ret);
// 关闭该handle
dlclose(handle);
return 0;
}
cat test.c
int get_card_index(int num)
{
return 123;
}
cat test.h
int get_car_index(int num);
编译和执行过程
syli@lishengyu-pc:~/work/tmp$ gcc -fPIC -shared -o liba.so test.c
syli@lishengyu-pc:~/work/tmp$ gcc dlopen.c -ldl
syli@lishengyu-pc:~/work/tmp$ ./a.out
ret:123