0
votes

I have a DLL that contains both code (exported functions) as well as data (binary data embedded as a resource).

This DLL is statically linked into my program (EXE). In order to get access to the binary data in the DLL, I need a handle (HMODULE) of this DLL so I can pass this handle to Win32 APIs like FindResource() et al.

My query is which function - LoadLibrary() or GetModuleHandleEx() - I should be using on this statically linked DLL so that the returned handle is guaranteed to be non-NULL (ie valid).

I referred to MSDN docs on GetModuleHandleEx(). It says that this API is to be used to get the handle of already loaded modules but it does not say what the behavior will be when it's used on statically linked (which can also be assumed to be already loaded) DLLs.

LoadLibrary() serves me just fine but my concern is if it will incur extra overhead in loading the statically linked DLL again into my program's address space? or will using LoadLibrary() merely increment the ref count of the DLL?

1
Best way is for the DLL to export a function that returns its HMODULE. This also gives you flexibility to change language/data by returning a different module. MFC uses this technique. - Raymond Chen
the GetModuleHandle is enough in your case - dll already loaded - RbMm
@RaymondChen So essentially, you're saying that we store the HMODULE argument passed to DllMain() the very first time (DLL_PROCESS_ATTACH) into a global variable (of type HMODULE) and return this global variable in the exported function? - Anurag S Sharma
Yes. Return that global variable, or possibly load your own library and return the handle to that other library (if you want to change language/datA). - Raymond Chen

1 Answers

2
votes

Statically linked .DLLs are pinned, they cannot be unloaded. LoadLibrary and GetModuleHandle have the same behavior on pinned .DLLs (assuming you pass in the correct name).

LoadLibrary will increment the reference count (on non-pinned) .DLLs but it will not change the address space. Calling LoadLibrary on a path that is not already loaded will of course load a new module where as GetModuleHandle will fail. If you pass in a filename without a path they will act on a already loaded .DLL, if present.