您好,我正在尝试实现共享库(动态链接),下面是我遇到错误的代码,请帮助我修复它
error: invalid conversion from ‘void*’ to ‘double (*)(int*)’ [-fpermissive]
fn = dlsym(lib_handle, "ctest1");
ctest1.c
void ctest1(int *i)
{
*i=5;
}
上面的ctest1.c是下面hello.cc文件中使用的共享库
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "ctest1.h" // here i have declared the function of shared library
int main(int argc, char **argv)
{
void *lib_handle;
void (*fn)(int *);
int x=990;
char *error;
lib_handle = dlopen("libp.so", RTLD_LAZY); // opening the shared library
if (!lib_handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
fn = dlsym(lib_handle, "ctest1"); //storing the address of shared library function
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(1);
}
fn(&x);
printf("getting x value from shared library=%d\n",x);
dlclose(lib_handle);
return 0;
}
~
~
~
最佳答案
您只是调用了错误的编译器。在 c++你不能从 void *
转换为另一种指针类型而不进行强制转换。如果这不是您的代码,则缺少转换意味着代码是 c而不是 c++ .请阅读标签 wiki 以了解,c 和 c++ 不是同一种语言,它们有些相似,但肯定不相同。
这是来自 c 的草案 n1570标准
6.3.2.3 Pointers
- A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
如果这是您的代码,您应该通过使用适当的文件扩展名来区分 c 和 c++,或者强制编译器使用我不推荐的适当的编译器,只需修复文件扩展名。
关于c++ - 共享库错误为 "invalid conversion"从 void * 到 double(*) (int*)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33064899/