c++ - 共享库错误为 "invalid conversion"从 void * 到 double(*) (int*)?

标签 c++ c shared-libraries dynamic-linking

您好,我正在尝试实现共享库(动态链接),下面是我遇到错误的代码,请帮助我修复它

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;
}

~
~
~

最佳答案

您只是调用了错误的编译器。在 你不能从 void * 转换为另一种指针类型而不进行强制转换。如果这不是您的代码,则缺少转换意味着代码是 而不是 .请阅读标签 wiki 以了解,c 和 c++ 不是同一种语言,它们有些相似,但肯定不相同。

这是来自 的草案 n1570标准

6.3.2.3 Pointers

  1. 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/

相关文章:

c++ - 我可以从运行时加载的共享对象访问主机进程的符号吗?还有其他选择吗?

c++ - 共享库 C++ Makefile

c++ - 帧缓冲对象错误?

c++ - 理解 8 皇后拼图的对角搜索

c++ - 为什么我可以捕获一个对象或 dynamic_cast 即使它的 std::type_info 对象不同?

c - 向预分频硬件定时器添加偏移量时,如何避免这种差一错误?

c - 重新分配三重指针

c++ - 用于 smtps 的窗口 api

c++ - 如何在 OpenCv 中轻松检测 2 个 ROI 是否相交?

javascript - 像 Javascript 对象的方法一样重写 C++ 对象的方法?