Joh*_*itb 21
dlo.c代码(lib):
#include <stdio.h>
// function is defined in main program
void callb(void);
void test(void) {
printf("here, in lib\n");
callb();
}
Run Code Online (Sandbox Code Playgroud)
编译
gcc -shared -olibdlo.so dlo.c
Run Code Online (Sandbox Code Playgroud)
这里是主程序的代码(从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);
}
Run Code Online (Sandbox Code Playgroud)
用.构建
gcc -ldl -rdynamic main.c
Run Code Online (Sandbox Code Playgroud)
输出:
[js@HOST2 dlopen]$ LD_LIBRARY_PATH=. ./a.out
here, in lib
here, i'm back
[js@HOST2 dlopen]$
Run Code Online (Sandbox Code Playgroud)
该-rdynamic选项将所有符号放在动态符号表中(映射到内存中),而不仅仅是所用符号的名称.在这里进一步了解它.当然,您还可以提供定义库与主程序之间接口的函数指针(或函数指针结构).这实际上是我可能选择的方法.我从其他人那里听说,-rdynamic在Windows中做起来并不容易,而且它还可以使库和主程序之间的通信更加清晰(你可以对可以调用的内容进行精确控制而不是),但它还需要更多家政.
| 归档时间: |
|
| 查看次数: |
3938 次 |
| 最近记录: |