Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 881
User48765902 Avatar asked Aug 16 '10 21:08

User48765902


People also ask

What does LoadLibrary return?

LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. LoadLibrary can also be used to load other executable modules.

Can you load the same DLL twice?

You can not load the same DLL multiple times into a single process (or not and have any effect). If you make the DLL a COM host and use COM objects then this will be automatically handled by each class instance.

Which DLL is LoadLibrary?

Kernel32. dll is loaded into every Windows process, and within it is a useful function called LoadLibrary .

What is GetProcAddress?

GetProcAddress verifies that the specified ordinal is in the range 1 through the highest ordinal value exported in the . def file. The function then uses the ordinal as an index to read the function's address from a function table.


2 Answers

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.

like image 55
Peter Ruderman Avatar answered Oct 13 '22 08:10

Peter Ruderman


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

like image 8
Benjamin Anderson Avatar answered Oct 13 '22 10:10

Benjamin Anderson