c - 如何检查dlsym中函数指针的返回值?

标签 c shared-libraries

我正在编写一个库,它将使用 dlopen 加载动态库并调用给定的函数。

我的函数指针需要一个返回类型为 int 的函数指针。

typedef int (*function_handle)(int); 

一个函数的返回类型在共享对象中是void。

 void some_function_ret_void(int b)

但是如果我将这个指针分配给 fn,dlsym 不会抛出任何错误。

typedef int (*function_handle)(int);
function_handle fn;

有没有办法检查从 dlsym 得到的函数指针的返回值?

#include <dlfcn.h>
#include <stdio.h>
typedef int (*function_handle)(int);
int main()
{
  void* handle=dlopen("./libtest.so",RTLD_LAZY);
  function_handle fn;
  int retval =0;
  char *err;
  /**** How to check the return type of fn *********/

  fn=dlsym(handle, "some_function_ret_void");
  if ((err = dlerror()) != NULL) {
    printf("Could not invoke the handler %s",err);
    dlclose(handle);
    return 0;
  }

  /* 
    if(fn return type is void don't print anything)

    if(fn return type is char* , print the charecter) 
         free(str);
  */

  retval = fn(4);
  printf("%d",retval);  
  dlclose(handle);
  return 0;
}

在libtest.c(libtest.so)中

int some_function_ret_int( int a) {
     return a+10;
}

char* some_function_ret_str(int b) {
 //allocate memory for string and return;
}

void some_function_ret_void(int b) {
 //allocate memory for string and return;
}

最佳答案

不,没有办法检查dlsym() 的返回值。

dlsym() 中没有返回值智能 - dlsym() 甚至不知道您的符号是函数指针还是数据指针。除了依赖 dlsym() 的返回值/类型之外,您可能应该考虑其他实现设计的方法。

The dlsym() function shall search for the named symbol in all objects loaded automatically as a result of loading the object referenced by handle.

http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html

关于c - 如何检查dlsym中函数指针的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341397/

相关文章:

c - SSE _mm_load_pd 在 _mm_store_pd 段错误时工作

shared-libraries - Xcode : relative path on embedded binaries

linux - libtool 库版本编号

c - 静态函数和变量在共享库中导出

c - UDP 套接字 - 服务器未收到任何数据

c - 如何用C语言将树数据写入文件?

c++ - Windows Python C 扩展仅适用于我自己的 Python 构建(使用 VC++ 2008 Express 的 32 位构建)

c++ - 确定使用 dlopen 打开的动态库路径的可移植方法

c - 避免过于具体的依赖关系

c - 插入到哈希表中