views:

47

answers:

3

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?)

+2  A: 

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.

Peter Ruderman
Note that it is possible to get multiple instances if you use different paths resolving to the same DLL, but most people don't run into this.
Michael
Good catch. Thanks, Michael.
Peter Ruderman
A: 

If they are the same DLL, then it won't load it again.

http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx

"If the specified module is a DLL that is not already loaded for the calling process, the system calls the DLL's DllMain function with the DLL_PROCESS_ATTACH value. If DllMain returns TRUE, LoadLibrary returns a handle to the module. If DllMain returns FALSE, the system unloads the DLL from the process address space and LoadLibrary returns NULL. It is not safe to call LoadLibrary from DllMain. For more information, see the Remarks section in DllMain."

"If lpFileName does not include a path and there is more than one loaded module with the same base name and extension, the function returns a handle to the module that was loaded first."

Benjamin Anderson
A: 

No, it doesn't. To get around this, you can copy the .dll to a temporary file (as many times as you need to load the .dll) and then delete the files once you're done.

Eric Finn