传递给dlsym函数指针的类上的C ++ Segmentation错误

时间:2014-03-19 13:45:30

标签: c++ dll segmentation-fault shared-libraries

我正在尝试使用以下unmangled函数实现共享库:

extern "C" IGraphLib*   load_lib(const Param* p)
{
  std::cout << p << std::endl; // 0x1cf7050
  std::cout << p->getWidth() << std::endl; // segfault
  return new NibblerOpenGL(p);
}

我不明白为什么在尝试获取p的宽度时会出现分段错误,因为指针已分配。我按如下方式调用load_lib函数:

    IGraphLib*  LibLoader::load(const std::string& file, const Param* p)
    {
      this->_dlhandle = dlopen(file.c_str(), RTLD_LAZY);
      if (this->_dlhandle == NULL)
      {
        std::cerr << dlerror() << std::endl;
        return NULL;
      }
      IGraphLib*    (*loadFunc)(const Param*);

      loadFunc = reinterpret_cast<IGraphLib* (*)(const Param*)>(dlsym(this->_dlhandle, "load_lib"));
      if (loadFunc == NULL)
      {
        std::cerr << dlerror() << std::endl;
        return NULL;
      }
      std::cout << p << std::endl; // 0x1cf7050
      std::cout << p->getWidth() << std::endl; // works
      IGraphLib*    inst = loadFunc(p);

      return inst;
   }

load_lib函数中p的实例是相同的,所以我看不出为什么我无法访问他的成员函数。

我尝试过但没有工作:

extern "C" IGraphLib* load_lib(const void* n)
{
   std::cout << ((const Nibbler*)(n))->getWidth() << std::endl;
   return new NibblerOpenGL((const Nibbler*)(n));
}

0 个答案:

没有答案
相关问题