问题
I'm using the LoadLibrary function to load a DLL in Windows. My question is this: If I call this method more than once for the same DLL, do I get handles to different instances of the DLL, or will they all refer to the same instance?
Additionally, how does this behaviour correlate to Linux SO files, is it the same or completely different, and what assumptions can I make in this regard? Thanks.
回答1:
The MSDN documentation states:
The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count).
So it would appear that loading the module more than once (without matching calls to FreeLibrary) will return the same handle.
回答2:
If the DLL is already loaded, LoadLibrary will simply return the address of the library in memory. However, DllMain is not called again with DLL_PROCESS_ATTACH when the second load is attempted. Handles in the sense of libraries are just memory locations, so the value you get the second time around should be the same as the first.
As far as linux SO files go, I don't see why they would load twice either. However, someone else will have to weigh in on this to give you a proper answer.
回答3:
For Linux shared objects, from the dlopen(3) manpage:
If the same library is loaded again with
dlopen(), the same file handle is returned. Thedllibrary maintains reference counts for library handles, so a dynamic library is not deallocated untildlclose()has been called on it as many times asdlopen()has succeeded on it. The_init()routine, if present, is only called once. But a subsequent call withRTLD_NOWmay force symbol resolution for a library earlier loaded withRTLD_LAZY.
来源:https://stackoverflow.com/questions/9190801/load-a-dll-more-than-once