c++, multiple instances of a dll, singleton

若如初见. 提交于 2019-12-10 19:18:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!