2

This question asks how to retrieve the handle of the DLL that contains the currently executed code. A link in one of the answers suggests taking the address of __ImageBase as module handle. This works for me.

My question is: Given that it is so astonishingly simple to retrieve the current module's handle, why do frameworks like MFC (and even the code base I inherited) usually store the instance handle passed to DllMain() in some global variable? Is there a reason not to rely on __ImageBase?

Edit: According to Raymond Chen, __ImageBase is for Microsoft linkers only. There is another question that has more precise answers, including a linker-independent way using GetModuleHandleEx(). There is also a solution for Win2000 and earlier using VirtualQuery(). The question remains valid: Why saving the base address when it can be retrieved easily?

Roman R.
  • 68,205
  • 6
  • 94
  • 158
krlmlr
  • 25,056
  • 14
  • 120
  • 217
  • 1
    From the looks of it, MFC predates both __ImageBase and GetModuleHandleEx, so that's easily explained. Your code base might also predate them, or the original programmers might not have known about them. Saving the module handle is a perfectly good solution, so there would have been no reason for anyone to go looking for other options. – Harry Johnston Feb 21 '12 at 21:14
  • Except that you need to pass the handle to functions that are not aware of where it is stored. -- The historic background is a good point, too. – krlmlr Feb 22 '12 at 19:02

1 Answers1

6

__ImageBase is a trick provided by the Microsoft linker and might not work with other compilers/linkers. Even if the framework does not support other toolsets they might not know about this magic symbol so that is probably why it is not used much.

The same thing can be done in pure WinAPI with VirtualQuery or GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,...)

Roman R.
  • 68,205
  • 6
  • 94
  • 158
Anders
  • 97,548
  • 12
  • 110
  • 164
  • Thank you. My question was more about the design issue -- storing a value vs. "computing" it. – krlmlr Feb 21 '12 at 03:12
  • 1
    __ImageBase is still stored somewhere, probably in the relocation section of the PE file. Computing it is both slower and requires more code. – Anders Feb 21 '12 at 03:27