Linux下C如何调用动态库

本文深入探讨了如何使用gcc编译动态库,并通过C语言程序调用动态库中的函数,包括dlopen、dlsym、dlclose等关键函数的使用方法及原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先生成一个测试用的动态库,代码如下myso.c

#include <stdio.h>

void Hello()
{
  printf("Hello\n");
}

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.\n[%s]\n", error);
    return -1;
  }

  //get function address
  Hello = (void(*)())dlsym(handle, "Hello");
  error =  dlerror();
  if ( error != NULL )
  {
    printf("Fail to get function address.\n[%s]\n", 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.\n[%s]\n", error);
    return -1;
  }
  //implement the function
  char cstr_name[10] = "hjchen";
  char *cstr_return_name = myFunc(cstr_name);
  printf("%s\n", 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*类型的错误信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值