I need to load a DLL from within another DLL. The temptation is to load it in DllMain, but there is already convincing documentation which says that it is a “bad idea”.
At the risk of asking a question that is not very specific: Is there a best practice of loading a DLL from another DLL?
In our current project, our main DLL has a class. I load the second DLL from the constructor of that class. However, since that class can be instantiated multiple times in the DLL, I keep a variable around that indicates whether the DLL was previously loaded in order not to call LoadLibrary again. This somehow doesn’t feel like it is a good solution, hence my question.
It depends on your DLL.
Basically, you have these options:
If you choose 1, you’ll get really weird messages, if DLL2 is missing when you try to load DLL1, something like “Failed to load DLL1”. And the customer will never know that it’s because of missing DLL2. So I don’t like to use this solution, if you are not 100% sure that DLL2 is correctly installed.
When you load DLL2 by hand (LoadLibrary), however, you get a chance to present a meaningful message.
You can choose 2 if you have clear entry and exit points in your DLL. This is the case if your DLL exports one or very few functions, i.e. a function to create factory for other objects. Then you can load/unload with the factory.
You can choose 3, if this doesn’t cause you to do this load/unload frequently.
Futhermore, you have no need to keep only one handle to DLL2. You can call LoadLibrary/FreeLibrary multiple times, and it’s the framework who does the reference counting.
So, as your situation allows, you can choose one of these 3 solutions. You’ll have to use your original solution only if you have no clear entry point and you are calling the function, which requires DLL2, too often.