I’m making a DLL that dynamically loads another DLL (winsock) using LoadLibrary. I read that I should not call LoadLibrary in DllMain, but I use it repeatedly and don’t want to have to call LoadLibrary/GetProcAddress each time I use it. So my questions are:
-
Where is the best place to call LoadLibrary within a DLL?
-
How fast is LoadLibrary/GetProcAddress? Is it a lot of overhead to do so in each function?
Create an initialization function that does setup outside of DllMain. Your code calls that function after the DLL is loaded, which can then call whatever it needs to to finish initializing.
Calling LoadLibrary() should only be done one time. It is expensive because the OS has to make sure all dependencies are loaded before continuing as well as reserve the space in the process. If the DLL is already loaded, this is a lot faster than if it has to be loaded from disk.
GetProcAddress() should also really only be called one time per function (ideally). The function has to walk the export table of the DLL and locate the function by name. This involves string comparisons to locate the address. You want to cache the address for later so you can just call it directly next time.