Possible Duplicate:
How do I get the HMODULE for the currently executing code?
I'm trying to find a resource in my own module. If this module is an executable, that's trivial - GetModuleHandle(NULL)
returns the handle of the "main" module.
My module, however, is a DLL that is loaded by another executable. So GetModuleHandle(NULL)
will return the module handle to that executable, which is obviously not what I want.
Is there any way to determine the module handle of the module that contains the currently running code? Using the DLL's name in a call to GetModuleHandle()
seems like a hack to me (and is not easily maintainable in case the code in question is transplanted into a different DLL).
How to Apply the Guideline. To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.
The conventional approach to reduce this kind of code duplication is to move the common code to a member function, which can be called from all the constructors. Usually, that member function is called init.
Duplicated code is considered one of the worse code smells. Beyond blatant copy paste, there are subtle duplications like parallel inheritance hierarchies and repetitive code structures.
1. Duplicate code makes your program lengthy and bulky : Many programmers feel that if the software is working properly there is no reason to fix code duplications. You forget that you are just un-necessarily making your software bulky.
Store the module handle away when it is given to you in DllMain and then use it later when you actually need it. A lot of frameworks (e.g., MFC) do this automatically.
If DLL is linked with MFC then there is a way to get instance of the DLL in which some function was called:
void dll_function()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
HINSTANCE dll_instance = AfxGetInstanceHandle();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With