Archive for October, 2006

Dynamic Linking Loader Call Under UNIX

UNIX下的.so动态库调用由下面几个函数组成。

dlopen
原型:void *dlopen(const char *pathname, int mode);
类似windows下的LoadLibrary,pathanme是动态库的路径和名字,mode是动态库调用方式,返回库句柄,类似文件指针的东西。

dlsym
原型:void *dlsym(void *handle, const char *name);
类似windows下的GetProcAddress,handle是dlopen返回的库句柄,name是动态库内部函数或数据的名称,返回函数或数据的指针。

dlclose
原型:int dlclose(void *handle);
这个比较简单,类似windows下的FreeLibrary,handle就是dlopen的库句柄。正确关闭返回0,,非0都是错误代码。

简单的例子,来自SCO UNIX帮助文件。

#include <dlfcn.h>
void *handle;
int i, *iptr;
int (*fptr) (int);

handle = dlopen(“/usr/mydir/libx.so”, RTLD_LAZY);
fptr = (int(*)(int))dlsym(handle, “some_function”);
iptr = (int*)dlsym(handle, “int_object”);

i = (*fptr)(*iptr);

dlclose(handle);

————————————-
Updated:
可以使用ldd命令来检查一个so动态库的依赖关系。

Leave a Comment