dlsym导入方法一次以供后续使用

  • 本文关键字:一次 方法 导入 dlsym c
  • 更新时间 :
  • 英文 :


请考虑以下代码

shared.c

#include <stdio.h>
void printCharArray(char *someArray){
if (!someArray){
printf("someArray is null!n");
} else {
printf("Array is %sn", someArray);
}
}

question.c:

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#define LIB "/tmp/some.so"
void *handle = 0;
void localfunc();
int main(){
handle = dlopen(LIB, RTLD_LAZY);
if (!handle){
fprintf(stderr, "dlopen errn");
exit(1);
}
dlerror();
void (*printCharArray)() = dlsym(handle, "printCharArray");
char *err = dlerror();
if (err){
fprintf(stderr, "%sn", err);
exit(1);
}
printCharArray(); // some work
localfunc();
}

void localfunc(){
puts("localfunc");
dlerror();
void (*printCharArray)() = dlsym(handle, "printCharArray"); // <- This 
char *err = dlerror();
if (err){
fprintf(stderr, "%sn", err);
exit(1);
}
printCharArray(); // do some work in localfunc
}

编译并运行

2035  gcc -shared -o /tmp/some.so shared.c -fPIC
2036  gcc -ldl question.c

$ ./a.out 
someArray is null!
localfunc
someArray is null!

请注意,在localfunc中,我是如何再次调用dlsym来导入"printCharArray"的,这是以前在main()中完成的。我希望避免这种情况-如何在第一次导入后使用这种方法?(哦,我如何使我的第一个导入作为fn原型在question.c中的任何地方使用?(

将函数指针声明为全局变量,而不是main()的局部变量。

为其提供正确的参数声明,以便调用与定义匹配。然后用一个论点来称呼它。

在调用dlsym()之前调用dlerror()是没有意义的。如果你不把结果分配给某个东西,它就没有任何用处。

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#define LIB "/tmp/some.so"
void *handle = 0;
void localfunc();
void (*printCharArray)(char *);
int main(){
handle = dlopen(LIB, RTLD_LAZY);
if (!handle){
fprintf(stderr, "dlopen err: %sn", dlerror());
exit(1);
}
printCharArray = dlsym(handle, "printCharArray");
if (!printCharArray) {
char *err = dlerror();
printf(stderr, "%sn", err);
exit(1);
}
printCharArray(NULL); // some work
localfunc();
}

void localfunc(){
puts("localfunc");
printCharArray("something"); // do some work in localfunc
}

最新更新