在运行时链接和加载共享库 [英] Linking and loading shared libraries at runtime

查看:127
本文介绍了在运行时链接和加载共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read that you can use the dynamic linker API using dlfcn.h Here's a code example using the 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),并且在加载时更有用吗?,因为从示例中看,它似乎不是很有用.谢谢.

it loads and links the libvec.so shared library at runtime. But can someone explain when and how linking and loading .so's(DLL's on windows) at runtime is better and more useful instead at load time? Because looking from the example it doesnt seem very useful. Thanks.

推荐答案

但是有人可以解释在运行时何时以及如何链接和加载.so更好,更有用,而不是在加载时有用吗?

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

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

There are at least three relatively common use cases:

  • 可选功能(例如,如果IF libmp3lame.so可用,请使用它播放MP3.否则,该功能不可用).
  • 插件体系结构,其中主程序由第三方供应商提供,并且您可以开发使用主程序的自己的代码.这在例如迪斯尼(Disney),其中 Maya 用于常规模型操作,但是开发了专门的插件来对模型进行动画处理.
  • (上面的一个变体):在开发过程中加载和卸载库.如果程序花费很长时间来启动和加载其数据,并且您正在开发用于处理该数据的代码,则在不重新启动程序的情况下迭代(调试)代码的多个版本可能是有益的.您可以通过一系列dlopen/dlclose调用来实现这一点(如果您的代码没有修改全局状态,但是例如在其上计算一些统计信息).
  • optional functionality (e.g. IF libmp3lame.so is available, use it to play MP3s. Otherwise, the functionality is not available).
  • Plugin architecture, where the main program is supplied by 3rd-party vendor, and you develop your own code that uses the main program. This is common in e.g. Disney, where Maya is used for general model manipulation, but specialized plugins are developed to animate the model.
  • (A variant of above): loading and unloading the library during development. If a program takes a long time to start and load its data, and you are developing code to process this data, it may be beneficial to iterate over (debug) several versions of your code without restarting the program. You can achieve that by a sequence of dlopen / dlclose calls (if your code doesn't modify the global state, but e.g. computes some statistics over it).

这篇关于在运行时链接和加载共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆