windows 加载共享库的两个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3433522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:59:53  来源:igfitidea点击:

Loading two instances of a shared library

cwindowslinuxdll

提问by Nils Pipenbrinck

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?

采纳答案by Borealid

You can load a library twice, in theory, if it's compiled as position-independent code (-fPIC).

理论上,如果库被编译为与位置无关的代码 ( -fPIC) ,则您可以加载两次库。

On some Unices, you can then dlopenthe library twice if your loader has an RTLD_PRIVATEflag, 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.

在某些 Unices 上,dlopen如果您的加载程序具有RTLD_PRIVATE标志,或者通过具有相同符号的库的两个“不同”副本(将其放在两个不同的路径上,否则它将只返回第一个文件句柄),您可以两次使用该库, 并用RTLD_LOCAL.打开它们。

I don't know anything about Windows shared libraries. It may not even be possible.

我对 Windows 共享库一无所知。这甚至可能是不可能的。

回答by ruslik

On windows at least, you could just rename the library, and load both of them.

至少在 Windows 上,您可以重命名库,然后加载它们。