问题
I have got a DLL in which a singleton is defined.
I have got an app which can load multiple instances of this DLL.
The DLL needs a singleton instance per DLL instance, otherwise it will crash.
I observed that there was only one singleton instance for multiple DLL instances. Why? How can I resolved it (if possible, without refactoring the singleton into something else)?
Thanks for any help.
回答1:
You mentioned that you have multiple instances inside your app, which implies that they all live inside the same process.
Singletons like any other static member are limited to one per application regardless of whether they belong to an object loaded from a DLL etc.
回答2:
No way without refactoring your code. A DLL is "loaded" into the process space. Any static member defined in there is static for the process (a loaded DLL doesn't have its own memory).
You'll have to write a non-standard "singleton" to get multiple objects.
回答3:
And if you don't have the sources to the dll, then you must load it in different processes, one "singleton" per process. These could be simple child-processes to your main process that just handle the dll communication part.
Then of course, you must come with some communication scheme between your main process and your child processes, which will depend on how much you are using the dll. Is it just a couple of calls with a lot of data? Or a lot of different calls that differ from run to run?
Generally if you are using the dll to make more than a couple of simple calls it's probably easier to refactor your own code.
来源:https://stackoverflow.com/questions/4624768/c-multiple-instances-of-a-dll-singleton