One of the more useful techniques I've developed over the years is detecting what module the caller for a method came from.

In an application with multiple DLLs (or packages), sometimes, it's necessary to detect the module for the caller of a method.

In the System unit, there's a routine called FindHInstance, that, when given an address, returns the module handle for a module.

So, in the method where you wanted to know the module of a caller, you can do this:


This gets you the module handle of the module that called your method.

This method can be extended to find out what module an interface, or a class is defined as well.  One can do so by using the class itself.

For example, if you're a DLL and you want to find where TButton is declared, you need to cast it to a pointer first, and call FindHInstance like so:


Wrapping this into an easier to remember name, one can write:

 function FindClassHInstance(ClassType: TClass): HINST;
  Result := FindHInstance(Pointer(ClassType));

Then, you can call it like so:


FindClassHInstance is declared in the System unit.

This method can then be extended to find where the implementation for a particular interface is declared as well. In order to do this, cast the interface into an object, then obtain its class type, and finally, call FindClassHInstance on it.