Does LoadLibrary create distinct instances?

User48765902 picture User48765902 · Aug 16, 2010 · Viewed 10.6k times · Source

If I use the Win32 API LoadLibrary to load the same DLL 3 times in a row it should return 3 distinct handles and the functions in each library should all have different addresses correct? (Or does it do something "smart" and detect if the dll has already been loaded for the process and just point to the same module?)

Answer

Peter Ruderman picture Peter Ruderman · Aug 16, 2010

It does something smart. Windows keeps a reference count for each DLL loaded through LoadLibrary. That's why you have to call FreeLibrary once for each corresponding LoadLibrary call. Assuming you don't free the DLL first, each call to LoadLibrary will give you the same handle.

From the MSDN documentation for FreeLibrary:

Each process maintains a reference count for each loaded library module. This reference count is incremented each time LoadLibrary is called and is decremented each time FreeLibrary is called.