c++ - 如何知道 dlopen() 时没有 .so

标签 c++ plugins dlopen

我使用 dlopen 为我的项目制作了插件。

我想让我的主程序在没有这样的情况下停止尝试再次加载插件。

有什么好的解决办法吗? 我需要比较 dlerror 消息吗?

请帮帮我

最佳答案

来自manpage :

If dlopen() fails for any reason, it returns NULL.

还有一个非常广泛的例子。

EXAMPLE

The program below loads the (glibc) math library, looks up the address of the cos(3) function, and prints the cosine of 2.0. The following is an example of building and running the program:

$ cc dlopen_demo.c -ldl
$ ./a.out
-0.416147

Program source

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <gnu/lib-names.h>  /* Defines LIBM_SO (which will be a
                               string such as "libm.so.6") */
int
main(void)
{
    void *handle;
    double (*cosine)(double);
    char *error;

    handle = dlopen(LIBM_SO, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }

    dlerror();    /* Clear any existing error */

    cosine = (double (*)(double)) dlsym(handle, "cos");

    /* According to the ISO C standard, casting between function
       pointers and 'void *', as done above, produces undefined results.
       POSIX.1-2003 and POSIX.1-2008 accepted this state of affairs and
       proposed the following workaround:

           *(void **) (&cosine) = dlsym(handle, "cos");

       This (clumsy) cast conforms with the ISO C standard and will
       avoid any compiler warnings.

       The 2013 Technical Corrigendum to POSIX.1-2008 (a.k.a.
       POSIX.1-2013) improved matters by requiring that conforming
       implementations support casting 'void *' to a function pointer.
       Nevertheless, some compilers (e.g., gcc with the '-pedantic'
       option) may complain about the cast used in this program. */

    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    printf("%f\n", (*cosine)(2.0));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

关于c++ - 如何知道 dlopen() 时没有 .so,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296994/

相关文章:

c++ - 在第二维为常数的情况下制作动态二维数组会很愚蠢吗?

c++ - 如何将轴移动到 QCustomPlot 的中间

plugins - 如何在后台运行cordova插件?

c++ - 与 dlopen/dlsym 一起使用时 dynamic_cast 失败

c++ - 在运行时编译和 C++ 中的#include 自定义 header

c - 有没有办法找出一个进程中对动态库的引用数?

c++ - 关于C++虚函数继承的困惑

c++ - 匹配别名模板作为模板参数

javascript - 如何为动态 html 元素调用 jquery 插件?

authentication - 如何正确使用groovyx.net.http.RESTClient中的get方法