14

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

Community
  • 1
  • 1
Pepor
  • 1,042
  • 1
  • 8
  • 27

3 Answers3

13

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.

1800 INFORMATION
  • 131,367
  • 29
  • 160
  • 239
  • Could you please give some more details about this solution? I have got the same problem as author of the thread but I don't know what is the DllMain, when is it called and how can I store the information I need. – Marcin K. Apr 27 '17 at 13:12
  • @MarcinK. https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx - this explains what is DllMain. It is an optional entry point into your module that you can create and do things like store the module handle in a global variable. – 1800 INFORMATION May 01 '17 at 07:19
6

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();
  }
Sergey Maruda
  • 61
  • 1
  • 1
  • Thanks for the suggestion. For MFC DLLs that's a good solution. But about half my DLLs are not, so I needed something else, too. I haven't looked at the MFC source code, but they are probably also storing the handle when the DLL gets loaded. – Pepor Dec 02 '11 at 04:12
1

As has been already stated this can be done by saving the module handle passed in to the DllMain function.

But there are other reasons why you should save the handle.

For example if you decide to bind resources to the DLL using the resource linker, you will need this module handle to get at these resources via the LoadResource function API.

jussij
  • 10,370
  • 1
  • 33
  • 49