我正在编写一个库,它将使用 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/