dlo.c(lib)的代码:
#include <stdio.h>
// function is defined in main program
void callb(void);
void test(void) {
printf("here, in lib\n");
callb();
}
编译
gcc -shared -olibdlo.so dlo.c
这里是主程序的代码(从dlopen手册页复制,并调整):
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void callb(void) {
printf("here, i'm back\n");
}
int
main(int argc, char **argv)
{
void *handle;
void (*test)(void);
char *error;
handle = dlopen("libdlo.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
*(void **) (&test) = dlsym(handle, "test");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
(*test)();
dlclose(handle);
exit(EXIT_SUCCESS);
}
用
构建
gcc -ldl -rdynamic main.c
输出:
[js@HOST2 dlopen]$ LD_LIBRARY_PATH=. ./a.out
here, in lib
here, i'm back
[js@HOST2 dlopen]$
-rdynamic 选项将所有符号放入动态符号表(映射到内存)中,而不仅仅是使用符号的名称。进一步了解它here。当然,您也可以提供定义库和主程序之间接口的函数指针(或函数指针的结构)。这实际上是我可能会选择的方法。我从其他人那里听说,在 Windows 中执行 -rdynamic 并不容易,而且它还可以使库和主程序之间的通信更加清晰(您可以精确控制可以调用的内容和不可以调用的内容),但它也需要更多的家务。