Search code examples
c++visual-c++dllloadlibrarydynamic-loading

Loading a dll with LoadLibrary


If I load a DLL with LoadLibrary, is that DLL guaranteed to stay loaded? If not, how can I prevent re-loading.

Actual situation: I have a dispatcher which, depending on some messages, needs to load one of several dll's and execute some function from them. I can't link against them at compile time, so I use LoadLibrary. Because there can potentially be a lot of calls, I'd prefer not to have to call LoadLibrary every time, since it turns out it's a bottleneck. So I was thinking to only call it once per DLL, calling GetProcAddress to get the function also only once per dll, and cache it somewhere. But is it safe? Am I guaranteed that calling that function will be ok on any subsequent call? If not, how can I have this guarantee?


Solution

  • LoadLibrary increases the reference count of the executable, and FreeLibrary decreases it.

    When the reference count reach 0, the executable is unloaded. So you normally don't have to worry about it. As long as no one calls FreeLibrary in your process, the Dll will stay there.