For a test I'd like to load two instances of a shared library from an application. The code in the library provides an API but it does not allow me to initialize two (or more) instances of the library because some of the functions rely on static variables..
对于测试,我希望从应用程序加载共享库的两个实例。库中的代码提供了一个API,但是它不允许我初始化库的两个(或多个)实例,因为有些函数依赖于静态变量。
I'm currently writing unit-tests for this lib, and I'd like to have two instances because that would simplify my tests a lot.
我目前正在为这个库编写单元测试,我希望有两个实例,因为这会大大简化我的测试。
The library doesn't get linked into the program. Instead I load it directly using LoadLibrary/GetProcAddress (or dlopen/dlsym on linux). To distinguish the two libraries I could simply use different names for the function-pointers I'm loading...
这个库没有链接到程序中。相反,我使用LoadLibrary/GetProcAddress(或linux上的dlopen/dlsym)直接加载它。为了区分这两个库,我可以简单地用不同的名称来命名我正在加载的函数指针…
Here are the questions:
这是问题:
-
Is it possible to load such a library twice? E.g. All loaded instances of the library should get their own data-segment and don't influence each other.
这样的图书馆能装两次吗?例:该库的所有加载实例都应该有自己的数据段,并且不相互影响。
-
If so: Is this portable for windows and linux?
如果是这样:这是windows和linux的便携设备吗?
2 个解决方案
#1
8
You can load a library twice, in theory, if it's compiled as position-independent code (-fPIC
).
理论上,如果一个库被编译为独立于位置的代码(-fPIC),您可以加载它两次。
On some Unices, you can then dlopen
the library twice if your loader has an RTLD_PRIVATE
flag, or by having two "different" copies of the library with the same symbols (put it at two different paths, otherwise it will just return the first file handle), and opening them each with RTLD_LOCAL
.
一些尤尼克公司,然后可以dlopen图书馆两次如果你的装载机RTLD_PRIVATE国旗,或有两个“不同”的副本库使用相同的符号(在两个不同的路径,否则它将只返回第一个文件句柄),开放给每个RTLD_LOCAL。
I don't know anything about Windows shared libraries. It may not even be possible.
我对Windows共享库一无所知。这甚至是不可能的。
#2
3
On windows at least, you could just rename the library, and load both of them.
至少在windows上,您可以重命名库,并加载它们。
#1
8
You can load a library twice, in theory, if it's compiled as position-independent code (-fPIC
).
理论上,如果一个库被编译为独立于位置的代码(-fPIC),您可以加载它两次。
On some Unices, you can then dlopen
the library twice if your loader has an RTLD_PRIVATE
flag, or by having two "different" copies of the library with the same symbols (put it at two different paths, otherwise it will just return the first file handle), and opening them each with RTLD_LOCAL
.
一些尤尼克公司,然后可以dlopen图书馆两次如果你的装载机RTLD_PRIVATE国旗,或有两个“不同”的副本库使用相同的符号(在两个不同的路径,否则它将只返回第一个文件句柄),开放给每个RTLD_LOCAL。
I don't know anything about Windows shared libraries. It may not even be possible.
我对Windows共享库一无所知。这甚至是不可能的。
#2
3
On windows at least, you could just rename the library, and load both of them.
至少在windows上,您可以重命名库,并加载它们。