c - 动态库函数调用

标签 c linux dlsym

我有以下代码,它只是从当前目录加载库 test.so 并在该库中执行 version 函数。应该返回的是一个字符串。相反返回的是堆栈中的垃圾(可能是指针位置?)。有谁知道为什么以下代码会失败。

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int main(int argc, char **argv){
    void *handler;
    char *(*version);
    char *error;

    handler = dlopen("./test.so", RTLD_LAZY);
    if(!handler){
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }

    dlerror(); //Flushes any existing error

    *(void **)(&version) = dlsym(handler, "version");

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

最佳答案

更改声明:

char *(*version); // this is not a function pointer

到:

char *(*version)(); // but this is

然后,更改行:

printf("%s\n", version);

到:

printf("%s\n", version());

关于c - 动态库函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10374578/

相关文章:

java - 有没有什么方法可以调用清理函数来清理 native 代码,同时在 Android 中保留任何 Activity ?

c - 无法使用 dlsym 获取统计数据

c++ - 如何在写入发生之前获得文件更改的通知?

c - 再现 RAW 图像 - C

linux - 使用 gtkmm 设置自定义应用程序主题

python - 如何在 Docker 容器中对进程进行 numactl membind?

php - 从 Linux 子系统 SSH 到 wamp 服务器 apache/php

C --> malloc --> dlsym

c - 如何在 C 中访问(动态分配的)Fortran 数组

c - nftw 文件句柄总数或可用数量