Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get my own code's module handle? [duplicate]

Tags:

dll

winapi

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

like image 974
Pepor Avatar asked Sep 23 '08 07:09

Pepor


People also ask

How do you avoid code duplication?

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.

How do you avoid code duplication in C++?

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.

Is duplicate code a code smell?

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.

What is one of the primary reasons for not duplicating code?

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.


2 Answers

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.

like image 174
1800 INFORMATION Avatar answered Sep 21 '22 15:09

1800 INFORMATION


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();
  }
like image 38
Sergey Maruda Avatar answered Sep 17 '22 15:09

Sergey Maruda