User48765902
User48765902

Reputation: 371

Does LoadLibrary create distinct instances?

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

Upvotes: 28

Views: 13927

Answers (3)

Eric Finn
Eric Finn

Reputation: 9005

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.

Upvotes: 4

Benjamin Anderson
Benjamin Anderson

Reputation: 1384

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."

Upvotes: 8

Peter Ruderman
Peter Ruderman

Reputation: 12485

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.

Upvotes: 27

Related Questions