c++ - 在 C++ 中是否可以使用多个 dlopen 处理程序

标签 c++ c++11

<分区>

所以我有一个程序分为 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)似乎使用。从我所做的一些研究来看,似乎一个线程中只能有一个句柄。我不确定我说的是否正确,但如果我是的话。我该如何解决这个问题?

最佳答案

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

man dlopen

Will dlopen yield the same handle for two calls with the same file?

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

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

关于c++ - 在 C++ 中是否可以使用多个 dlopen 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57094938/

相关文章:

c# - 将 C# 集成到 C++ 中

c++ - 是否可以指定按位操作的返回类型?

c++ - 为什么在使用 try_lock() 时需要显式比较?

C++11 - 无法使用 std::thread 和 std::condition_variable 唤醒线程

c++ - 尝试编译 webdis 时出错

c# - HANDLE (IntPtr) 已过时,kernel32.dll,SafeFileHandle 到 IntPtr

c++ - 哈希函数和随机排列

c++ - nullptr 不能在 valarray 中使用

c++ - 理解可变参数模板函数

c++ - 为什么抛出局部变量调用 moves 构造函数?