Load a DLL More Than Once?

孤者浪人 提交于 2019-12-19 01:07:10

问题


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. The dl library maintains reference counts for library handles, so a dynamic library is not deallocated until dlclose() has been called on it as many times as dlopen() has succeeded on it. The _init() routine, if present, is only called once. But a subsequent call with RTLD_NOW may force symbol resolution for a library earlier loaded with RTLD_LAZY.



来源:https://stackoverflow.com/questions/9190801/load-a-dll-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!