检查符号是否可用,以防止 dlopen 延迟绑定失败

Check if a symbol is available, to prevent dlopen lazy binding failure

我使用 dlopen() 加载了一个 .so 库。图书馆调用 myfunc()。该函数在加载程序的版本 1.0 中可用。所以调用 myfunc() 是可行的。然而,在版本 0.9 中,没有 myfunc(),并且 libdl 显示有关延迟绑定失败的错误。

我能否在 so. 库中检查 myfunc() 是否存在,然后才调用该函数?该函数不是强制性的,不重要,如果加载器的版本为 0.9 或更低,我可以安全地跳过调用它。

在和ELF平台上,您可以使用弱未解析引用来实现您的目标:

// libfoo.c
extern int myfunc() __attribute__((weak));
int foo()
{
   if (&myfunc == NULL) {
     printf("myfunc is not defined\n");
   } else {
     // myfunc is available, call it
     printf ("myfunc returns %d\n", myfunc());
   }
}