c - 在运行时链接和加载共享库

标签 c linker operating-system dynamic-linking

我了解到您可以通过 dlfcn.h 使用动态链接器 API,这是使用该 API 的代码示例

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int x[2]={1,2};
int y[2]={3,4};
int z[2];

int main(){
  void *handle;
  void(*addvec)(int *,int *,int *,int);
  char *error;

  // Dynamically load shared library that contains addvec()
  handle=dlopen("./libvec.so",RTLD_LAZY);
  if(!handle){
    fprintf(stderr,"%s\n",dlerror());
    exit(1);
  }
  // Get a pointer to the addvec() function we just loaded
  addvec=dlsym(handle,"addvec");
  if((error=dlerror())!=NULL){
      fprintf(stderr,"%s\n",dlerror());
      exit(1);
  }
  // now we can call addvec() just like any other function
  addvec(x,y,z,2);
  printf("z=[%d %d]\n",z[0],z[1]);

  // unload the shared library
  if(dlclose(handle)<0){
      fprintf(stderr,"%s\n",dlerror());
      exit(1);
  }
  return 0;
}

它在运行时加载并链接 libvec.so 共享库。 但是有人可以解释一下何时以及如何在运行时链接和加载 .so(Windows 上的 DLL)而不是在加载时链接和加载更好和更有用吗?因为从示例来看它似乎不是很有用。谢谢。

最佳答案

But can someone explain when and how linking and loading .so's at runtime is better and more useful instead at load time?

至少有三个相对常见的用例:

  • 可选功能(例如,如果 libmp3lame.so 可用,则使用它来播放 MP3。否则,该功能不可用)。
  • 插件架构,其中主程序由第三方供应商提供,您开发自己的使用主程序的代码。这在例如迪士尼在哪里Maya用于一般模型操作,但开发了专门的插件来为模型制作动画。
  • (上述的变体):在开发过程中加载和卸载库。如果程序需要很长时间来启动和加载其数据,并且您正在开发代码来处理此数据,则在不重新启动程序的情况下迭代(调试)代码的多个版本可能会很有帮助。您可以通过一系列 dlopen/dlclose 调用来实现这一点(如果您的代码不修改全局状态,但例如计算一些统计数据)。

关于c - 在运行时链接和加载共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28795902/

相关文章:

linux - 使 GNU ld 或 GNU gold 显示存档中使用了哪些 .o 文件

c++ - 如何从C++动态调用汇编函数?

java - Java6 中 java.nio.file.Path 的替代方案,以实现操作系统文件系统灵活性

在 CMake 中创建一个包含所有静态链接(包括 libc)的 .so 文件

c - 在 C 中,两个相同的链并不将自己标识为相等

c - C 中使用的括号,不带 if、循环等控制结构

在C中将字符串MAC地址转换为char[6]

c++ - "only one implementation"规则的异常(exception)?

使用 fork() 进行 C 系统编程

android - cooking 安卓