Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Linux下C如何调用动态库

首先生成一个测试用的动态库,代码如下myso.c#include <stdio.h>
 
void Hello()
 {
 printf("Hello ");
 }
 
char * Func(char *cstr_name)
 {
 return cstr_name;
 }编译成动态库
 
gcc -shared -fPIC -o myso.so myso.c
 
下面程序调用动态库中的两个函数#include <stdio.h>
 #include <dlfcn.h>
 int main(int argc, char **argv)
 {
 char *error = NULL;
 void *handle = NULL;
 void (*Hello)();
 typedef char *(*Func)(char *);
 
  //load so file
 handle = dlopen("/home/hjchen/myso.so", RTLD_LAZY);
 error =  dlerror();
 if ( error != NULL )
 {
   printf("Fail to load so file. [%s] ", error);
   return -1;
 }
 
  //get function address
 Hello = (void(*)())dlsym(handle, "Hello");
 error =  dlerror();
 if ( error != NULL )
 {
   printf("Fail to get function address. [%s] ", error);
   return -1;
 }
 
  //implement the function
 Hello();
 
  //get function address
 Func myFunc = (Func)dlsym(handle, "Func");
 error =  dlerror();
 if ( error != NULL )
 {
   printf("Fail to get function address. [%s] ", error);
   return -1;
 }
 //implement the function
 char cstr_name[10] = "hjchen";
 char *cstr_return_name = myFunc(cstr_name);
 printf("%s ", cstr_return_name);
 
  //decrease amount of reference
 dlclose(handle);
 
  return 0;
 }
 
编译gcc -ldl -o loadso loadso.c。
 
需要加上链接库-ldl
 
 
 
整个调用过程主要用到四个函数
 
dlopen :加载动态库。参数:(动态库文件,加载模式);返回:如果加载失败返回NULL,成功返回一个非空指针。
 dlsym:获取动态库中函数地址。参数:(dlopen返回的指针,动态库中的函数名);返回:动态库中函数指针。
 dlclose:将动态库引用减一,如果达到0就把这个库从内存中移出去。参数:(dlopen返回的指针).
 
dlerror:获取报错信息。返回:char*类型的错误信息。