你不需要特殊的图书馆获得dlopen()
等在Mac OS X和共享对象.dylib
或.bundle
结束在Mac OS X
此代码,没有额外的库编译:
#include <dlfcn.h>
#include <stdio.h>
int main(int argc, char **argv)
{
char *name = "libc.dylib";
if (argc > 1)
name = argv[1];
void *dlh = dlopen(name, 0);
if (dlh == 0)
printf("Failed to dlopen() %s\n", name);
else
printf("Got handle %p from dlopen() for %s\n", dlh, name);
dlclose(dlh);
return 0;
}
它运行并且产生:
Got handle 0x7fff624e9378 from dlopen() for libc.dylib
汇编:
gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Werror dl.c -o dl
我在Mac OS X 10.9 Mavericks上使用GCC 4.8.2,但答案在任何版本的Mac OS X中仍然支持。
注意的ldd
在Mac OS X上的等价物是otool -L
,它产生:
$ otool -L dl
dl:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
/usr/gcc/v4.8.2/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
$
我不知道什么幕后的魔法诡计或意味着开放libc.dylib
实际上有效。但是:
$ ./dl libSystem.B.dylib
Got handle 0x7fff6e398378 from dlopen() for libSystem.B.dylib
$ ./dl
Got handle 0x7fff690d2378 from dlopen() for libc.dylib
$
这两个地址是相同的,所以可能会有一些映射在幕后进行。