Managed Hook allows you to hook any methods with a handler that is called before and after the hooked method is called.
Tested with X64 architecture with non-inlined methods.
(careful with optimized code with inlined methods, the pattern was not intended to be used in that case)
How to use:
1- Create a class that implements the interface IHookerHandler:
public class MyHookHandler : IHookHandler
{
public void Before(object instanceHooked, object[] parameters)
{
// do whatever you want here
}
public void After(object instanceHooked, object[] parameters)
{
// do whatever you want here
}
}
2- Get the methodInfo for the method to be hooked:
MethodInfo methodHooked = typeof(Foo).GetMethod("MethodHooked");
3- Hook the method!
HookManager.Instance.HookFunction(methodHooked, new MyHookHandler());
Or hook the method with lamdas (before call and after call)
HookManager.Instance.HookFunction(methodHooked, (t) => { ... }, (t) => { ... });
4 - (opt) When finished, you can unhook the method:
HookManager.Instance.UnHookFunction(methodHooked);
HookManager.Instance.HookFunction(methodHooked, new MyHookHandler());
That's it!
When the original method is called, it will automatically be forwarded to the created dynamic method.
Inside the generated method, it calls the handler that the client created.
The HookManager keeps all the hooks with the function pointer as the key.
(that's why we used the RBX register to know in which original function it was called)