【问题标题】:How to know there is no .so when dlopen()dlopen() 时如何知道没有 .so
【发布时间】:2017-06-01 01:16:04
【问题描述】:

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

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

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

请帮帮我

【问题讨论】:

    标签: c++ plugins dlopen


    【解决方案1】:

    来自manpage

    如果dlopen() 因任何原因失败,则返回NULL

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

    示例

    下面的程序加载(glibc)数学库,查找 cos(3) 函数的地址,并打印 2.0 的余弦。这 以下是构建和运行程序的示例:

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

    程序源

    #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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      相关资源
      最近更新 更多