linux动态链接库中函数的运行时加载


一.  相关函数:dlopen(打开共享库),dlsym(查找符号),dlerror(错误信息),dlclose(关闭共享库)

   1. dlopen()  

原型:void* dlopen(const char *filename, int flag);

   2. dlsym()

   3. dlerror()

   4. dlclose()

二. 源码实例

   1. 动态库文件:lib.c,lib.h    


#include <stdio.h>
void output(int index)
{
    printf("Printing from lib.so. Called by program %d\n", index);
}


#file:lib.h
#ifndef LIB_H
#define LIB_H
void output(int index);
#endif

  2. main.c

#include <stdio.h>
#include <dlfcn.h>
int main()
{
    void *handle;
    void (*fun)(int);
    char* error;
    handle = dlopen("/home/hotpatch/dynamic_lib/lib.so", RTLD_NOW);
    if(NULL == handle)
    {
        printf("Open library error.error:%s\n",dlerror());
        return -1;
    }
    fun = dlsym(handle,"output");
    if(NULL != (error = dlerror()))
    {
        printf("Symbol output is not found:%s\n",error);
        goto exit_runso;
    }
    fun(10);
    printf("Function address is: 0x%016x\n",fun);
exit_runso:
    dlclose(handle);
    return 0;
}


   3.编译运行

编译:
      gcc -fPIC -shared -o lib.so lib.c
      gcc -o test main.c -ldl
运行:
     Printing from lib.so. Called by program 10
     Function address is: 0x00000000e67ba604

 


你可能感兴趣的:(函数运行加载,linux动态链接库)