问题
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;
}
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.
回答1:
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:
- 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).
来源:https://stackoverflow.com/questions/28795902/linking-and-loading-shared-libraries-at-runtime