【问题标题】:Unable to call a pointer to function returning a pointer无法调用指向返回指针的函数的指针
【发布时间】:2010-08-06 05:52:09
【问题描述】:

我遇到了一个奇怪的问题。 我有两个文件 a.c 和 b.c 如下: 公元前:

#include <stdlib.h>

int *foo() {
  int *x;
  x = (int *) malloc(sizeof(int));
  *x = 4;
  return x;
}

我使用 gcc 将 b.c 编译为 b.so: $ gcc -o b.so -shared -fpic

交流:

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

int main() {
  void *hdl;
  hdl = dlopen("./b.so", RTLD_LAZY);
  int *((*fn)(void));
  int *x;
  x = (*fn)();
  fn = dlsym(hdl, "foo");
  printf("%d", *x);
}

我使用 gcc 编译 a.c:

$ gcc -fpic -ldl a.c

现在当我运行它时:

$ ./a.out 分段错误

我哪里错了? 这在 b.c 中的函数不返回指针时有效。

此外,我尝试使用 dlerror() 检查错误,但它没有报告任何错误。

【问题讨论】:

    标签: c pointers function-pointers


    【解决方案1】:

    通过检查,您在初始化之前使用了fn。它还没有指向foo,它还没有特别指向任何东西,我怀疑结果行为是未定义的。

    【讨论】:

    • 已初始化(或为其赋值),未定义。变量fn 是在使用之前定义的。
    • @Georg Fritzsche:Sie haben recht,danke。
    【解决方案2】:

    你没有找到符号并调用函数。

    当您执行x = (*fn)(); 时,它不会从b.c 调用函数foo

    您必须首先将符号加载到函数指针中。

      int *x;
      fn = dlsym(hdl, "foo");
      x = fn();
      printf("%d", *x);
    

    以上应该可以工作。

    编辑:

    dlopen,dlsym 的示例程序可以在 here 找到,其中包含相同的手册页信息。

    【讨论】:

    • 我使用相同的源来学习如何生成 .so 文件并使用它们:)
    【解决方案3】:

    可能只是您的示例有问题,但在您提供的代码中,您需要切换以下几行:

     x = (*fn)();
    fn = dlsym(hdl, "foo");
    

    【讨论】:

      【解决方案4】:

      这两行似乎顺序错误:

      x = (*fn)();
      fn = dlsym(hdl, "foo");
      

      【讨论】:

        猜你喜欢
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        相关资源
        最近更新 更多