Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading two instances of a shared library

Tags:

c

linux

windows

dll

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..

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...

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?

like image 900
Nils Pipenbrinck Avatar asked Aug 08 '10 07:08

Nils Pipenbrinck


People also ask

Can shared library use another shared library?

A library does not use another library as such. You reference the header library of shared library a from library b. They can both be shared. Then, when you link your executable you include both so files in the link stage.

How are shared libraries loaded?

Shared libraries are the most common way to manage dependencies on Linux systems. These shared resources are loaded into memory before the application starts, and when several processes require the same library, it will be loaded only once on the system. This feature saves on memory usage by the application.

Where are shared libraries loaded?

Shared Libraries are loaded by the executable (or other shared library) at runtime.

How do shared libraries work?

Simply put, A shared library/ Dynamic Library is a library that is loaded dynamically at runtime for each application that requires it. Dynamic Linking doesn't require the code to be copied, it is done by just placing name of the library in the binary file.


2 Answers

You can load a library twice, in theory, if it's compiled as position-independent code (-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.

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

like image 70
Borealid Avatar answered Sep 29 '22 23:09

Borealid


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

like image 45
ruslik Avatar answered Sep 29 '22 23:09

ruslik