首页 > 解决方案 > C++ 中是否可以使用多个 dlopen 处理程序

问题描述

所以我有一个程序分为 4 个部分。在前 3 部分中,我创建了 3 个不同的共享动态库,然后在第四部分中使用它们进行动态加载。

在第 4 部分中,我的程序结构大致如下所示

.hpp

...
typedef Snake *(*SNAKE)(int, int);
typedef void (*DELETESNAKE)(Snake *);

...

SNAKE _snake;
std::map<int, void *> _handlers;
std::map<int, Snake *> _snakes;
std::map<int, std::string> _libs;
...

.cpp

 ...
_handlers[1] = dlopen("lib/libSnakeSFML.so", RTLD_LAZY | RTLD_LOCAL);
if (!_handlers[1])
    throw NibblerExceptionE("dl_error : " + std::string(dlerror()));
_snake = reinterpret_cast<SNAKE>(dlsym(_handlers[1], "createSnake"));
if (!_snake)
    throw NibblerExceptionE("Some snake Error");
_snakes[1] = _snake(_w, _h);
_snakes[1]->init();

_handlers[2] = dlopen("lib/libSnakeSDL.so", RTLD_LAZY | RTLD_LOCAL);
if (!_handlers[2])
    throw NibblerExceptionE("dl_error : " + std::string(dlerror()));
_snake = reinterpret_cast<SNAKE>(dlsym(_handlers[2], "createSnake"));
if (!_snake)
    throw NibblerExceptionE("Some snake Error");
_snakes[2] = _snake(_w, _h);
_snakes[2]->init();

_handlers[3] = dlopen("lib/libSnakeFLTK.so", RTLD_LAZY | RTLD_LOCAL);
if (!_handlers[3])
    throw NibblerExceptionE("dl_error : " + std::string(dlerror()));
_snake = reinterpret_cast<SNAKE>(dlsym(_handlers[3], "createSnake"));
if (!_snake)
    throw NibblerExceptionE("Some snake Error");
_snakes[3] = _snake(_w, _h);
_snakes[3]->init();
...

现在,当我尝试动态调用任何方法时,似乎使用_snakes[...]了最后一个句柄,在这种情况下是。FLTK根据我所做的一些研究,似乎你只能在一个线程中拥有一个句柄。我不确定我说的是否正确,但如果我是的话。我该如何解决这个问题?

标签: c++c++11

解决方案


您可以与 dlopen 同时保持打开的库的数量非常大,并且基本上受您的地址空间限制。

男人打开

dlopen 会为具有相同文件的两个调用产生相同的句柄吗?

在那里你甚至可以找到一个将句柄存储在数组中的示例,就像你似乎做的那样,显然它工作得很好:manydl.c

我只是不禁想知道为什么您不只是让链接器将您的库链接到您的可执行文件。


推荐阅读