我正在尝试实现一个程序,我需要将一个类实例从我的主程序传递到我的共享库函数,用dlsym()动态打开。
我按如下方式加载我的lib:
IGraphLib* LibLoader::load(const std::string& file)
{
this->_dlHandle = dlopen(file.c_str(), RTLD_LAZY);
if (this->_dlHandle == NULL)
{
std::cerr << dlerror() << std::endl;
return NULL;
}
IGraphLib* (*loadFunc)();
loadFunc = reinterpret_cast<IGraphLib* (*)()>(dlsym(this->_dlHandle, "load_lib"));
if (loadFunc == NULL)
{
std::cerr << dlerror() << std::endl;
return NULL;
}
IGraphLib* inst = loadFunc();
return inst;
}
然后,在我的主程序中,我调用函数'test',即刚加载的库中类的实例的成员函数。
Nibbler* game = NULL;
game = new Nibbler(...)
lib = loader->load(av[3]);
lib->test(game);
共享库中的测试函数:
void NibblerSDL::test(Nibbler* game) const
{
std::cout << game->getWidth() << std::endl;
}
最后是valgrind错误,它说客户端正在切换堆栈,所以我猜问题会来自这里,我做了一些研究,我尝试用-rdynamic标志进行编译,但是没有改变任何事情:
==5954== Warning: client switching stacks? SP change: 0x7fefff4c8 --> 0x4ea670a35219e347
==5954== to suppress, use: --max-stackframe=5667340993508798079 or greater
==5954== Use of uninitialised value of size 8
==5954== at 0x40172EC: __longjmp (in /lib64/ld-2.18.so)
==5954==
==5954== Jump to the invalid address stated on the next line
==5954== at 0x7C9670A35219E1A7: ???
==5954== Address 0x7c9670a35219e1a7 is not stack'd, malloc'd or (recently) free'd
==5954==
==5954== Can't extend stack to 0x4ea670a35219d400 during signal delivery for thread 1:
==5954== no stack segment
==5954==
==5954== Process terminating with default action of signal 11 (SIGSEGV)
==5954== Access not within mapped region at address 0x4EA670A35219D400
==5954== at 0x7C9670A35219E1A7: ???
==5954== If you believe this happened as a result of a stack
==5954== overflow in your program's main thread (unlikely but
==5954== possible), you can try to increase the size of the
==5954== main thread stack using the --main-stacksize= flag.
==5954== The main thread stack size used in this run was 8388608.
==5954== Invalid write of size 8
==5954== at 0x4A22700: _vgnU_freeres (in /usr/lib64/valgrind/vgpreload_core-amd64-linux.so)
==5954== Address 0x4ea670a35219e2bf is not stack'd, malloc'd or (recently) free'd
==5954==
==5954==
==5954== Process terminating with default action of signal 11 (SIGSEGV)
==5954== General Protection Fault
==5954== at 0x4A22700: _vgnU_freeres (in /usr/lib64/valgrind/vgpreload_core-amd64-linux.so)
==5954==
库的load_lib函数:
extern "C" IGraphLib* load_lib()
{
return new NibblerSDL();
}