Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

c - Loading two instances of a shared library

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...