Keeping separate instances of a DLL's static memory
I'm currently attempting to integrate a DLL (FooEmulation
) into an existing project.
The DLL assumes that it will only be used to emulate one Foo
at a time, and uses a lot of static globals as a result.
Foo
instances at once.
I have the source to the original DLL, so I could convert all of the static globals into parameters that would be passed in (whether directly or via a handle), but the DLL is being maintained separately and I'd like to avoid forking/merging if at all possible.
One technique I found was to load multiple dynamically generated copies of the DLL, but that is too resource-heavy for the scale I need.
I also can't afford to create a process or thread for each Foo
.
Is it possible to keep multiple copies of the DLL's static memory and restore it per use of the DLL?
How do I locate it? Am I even allowed to touch it?When you load the DLL multiple times into the same process all the static data is shared, period. You'll have to redesign the library so that all those objects can be created dynamically as you need them during the runtime.
I am assuming you're on windows since there's nothing telling me otherwise..
Take a look here, which is the documentation for DLLMain in Windows. DLLMain has a parameter that tells you if
- A process is attaching (loading your DLL)
- A process is detaching (unloading your DLL)
- A thread is attaching (loading the per thread parts of your DLL)
- A thread is detaching (unloading the per thread parts of your DLL)
If you catch the process or thread events and allocate (attach) / free (detach) a new instance of your statics, I think this would solve your problem. It's a little hacky, but it would work... You have to be careful what you do in DLLMain as well. Look in the docs for the warnings about blocking in any way in DLLMain.
精彩评论