Hook

MonoMod.RuntimeDetour.Hook redirects calls to a managed method (the source) to your own method or delegate (the target), optionally letting the target call the original. It is the main API of MonoMod.RuntimeDetour and replaces the older Detour type. This page covers every constructor, the exact signature rules the target must follow, lifetime, and the errors you can hit.

Basic Usage

using MonoMod.RuntimeDetour;

// source: the method being hooked; target: the method that runs instead
using (var h = new Hook(methodInfoFrom, methodInfoTo))
{
    // While the Hook is alive and applied, calls to methodInfoFrom go to methodInfoTo.
}
// Disposed: the hook is undone.
Property Value
Namespace MonoMod.RuntimeDetour
Assembly / package MonoMod.RuntimeDetour
Implements IDetour (which extends IDisposable)
Applied by default Yes (applyByDefault defaults to true)
Default config DetourContext.GetDefaultConfig() (the ambient detour context)
Default factory DetourContext.GetDefaultFactory(), falling back to DetourFactory.Current

Constructor Overloads

Hook has many constructors. They are combinations of four independent choices:

Choice Options
How the source is given MethodBase source, Expression<Action> source, or Expression source
How the target is given MethodInfo target, MethodInfo target + object? targetObj, Expression/Expression<Action> target (+ optional targetObj), or Delegate target
Ordering optional DetourConfig? config
Activation optional bool applyByDefault

The most explicit forms, which every other overload forwards to, take an IDetourFactory as well:

public Hook(MethodBase source, MethodInfo target, object? targetObject,
            IDetourFactory factory, DetourConfig? config, bool applyByDefault);

public Hook(MethodBase source, Delegate target,
            IDetourFactory factory, DetourConfig? config, bool applyByDefault);
Parameter Type Meaning
source MethodBase The method to hook. Constructors are allowed (ConstructorInfo is a MethodBase).
target MethodInfo The method to run instead.
targetObject / targetObj object? The this object for a non-static target. Must be null for a static target.
target (delegate form) Delegate Any delegate. A single-cast delegate uses its Method and Target; a multicast delegate is called through its Invoke method.
factory IDetourFactory The detour engine to use. Normally left to the default.
config DetourConfig? Ordering information. See Detour Order.
applyByDefault bool Apply at the end of the constructor. Default true.

Expression-Tree Overloads

The Expression overloads let you name methods without reflection strings. Each expression must be a single method call; MonoMod casts the body to MethodCallExpression and takes its Method:

using var h = new Hook(
    () => default(Player)!.TakeDamage(default),   // source
    () => MyHooks.TakeDamage(default!, default!, default)); // target

Anything other than a method call (a property access, a lambda with several statements) fails with an InvalidCastException. The test suite uses this pattern with default(T) arguments, which are never evaluated.

Target Signature Rules

When the hook is created, MonoMod compares signatures using MethodSignature, where an instance source has its this type as an explicit first parameter:

  1. Plain replacement. The target's parameters (ignoring the target's own this) must be compatible with the source's parameters, and the return types must be compatible.
  2. Replacement with orig. If the target has exactly one more parameter than the source, the first parameter is treated as the next delegate (usually named orig). The remaining parameters must be compatible with the source, and the delegate's Invoke signature must also be compatible with the source.

"Compatible" (from Extensions.IsCompatible) is looser than "identical". Two types are compatible if:

  • they are the same type, or one is assignable from the other (so object matches any reference type, which is handy for private types you cannot name),
  • one is an enum and the other is (compatible with) its underlying type,
  • one is a pointer or by-ref and the other is IntPtr,
  • both are pointers, or one is a by-ref and the other a pointer.

System.Enum and System.ValueType do not match enums or structs this way, because those base types are boxed reference types.

The orig Delegate

The orig delegate is backed by a trampoline method rented from a pool. Calling it invokes the next hook in the chain, or the original method if yours is the last. You may pass any arguments and do anything with the return value; you may also skip calling it to replace the method entirely.

Warning: Only call orig while your hook method is on the stack (during the hooked call). The documentation in docs/RuntimeDetour/Usage.md states that invoking it later is not thread-safe and is not guaranteed to call the chain as it exists at that moment. Do not store orig for later use.

Hooking Instance Methods

For an instance source, the hook receives the instance as an explicit parameter:

// source: public int Player.TakeDamage(int amount)

// Without orig:
static int TakeDamage_Replace(Player self, int amount) => 0;

// With orig (the delegate itself also takes `self`):
static int TakeDamage_Wrap(Func<Player, int, int> orig, Player self, int amount)
    => orig(self, amount) + 42;

new Hook(typeof(Player).GetMethod("TakeDamage")!,
         typeof(MyHooks).GetMethod(nameof(TakeDamage_Wrap), BindingFlags.Static | BindingFlags.NonPublic)!);

These shapes come straight from the unit tests (TestMethod_A(TestObject self, int a, int b) and TestMethod_B(Func<TestObject, int, int, int> orig, TestObject self, int a, int b)).

For a source declared on a value type, the this parameter is the by-ref form of that type, so use a delegate whose first parameter is ref TStruct (you will need a custom delegate type, because Func/Action cannot take ref parameters).

Instance Targets

A target can itself be an instance method. Pass the instance as targetObj:

class MyMod
{
    public int Bonus = 5;
    public int Wrap(Func<Player, int, int> orig, Player self, int amount) => orig(self, amount) + Bonus;
}

var mod = new MyMod();
using var h = new Hook(takeDamage, typeof(MyMod).GetMethod(nameof(MyMod.Wrap))!, mod);

Lambdas and closures work the same way through the Delegate overloads, because a delegate carries both a method and its target object. When the target is a static method and has no orig parameter, MonoMod uses it directly; otherwise it generates a small proxy method that loads the target object and the orig delegate before calling your method.

Lifetime: Apply, Undo, and Dispose

Member Effect
Apply() Adds the hook to the method's detour chain if it is not already applied. No-op if already applied.
Undo() Removes the hook from the chain if applied. No-op otherwise. The hook can be applied again later.
Dispose() Undoes the hook (unless the process or AppDomain is shutting down), returns the trampoline to the pool, and makes the object invalid.
Finalizer If the Hook is garbage collected without being disposed, the finalizer undoes it.

Apply() and Undo() on a disposed hook throw ObjectDisposedException.

Because a finalizer undoes the hook, a hook you do not keep a reference to will disappear at some unpredictable point after the next garbage collection. Store hooks in a field (or a list) for as long as they should be active. To refer to a hook without keeping it alive, use its DetourInfo.

Properties

Property Type Description
Source MethodBase The hooked method, normalized with PlatformTriple.Current.GetIdentifiable(source).
Target MethodInfo The target method you supplied (for a delegate, its Method, or Invoke for a multicast delegate).
Config DetourConfig? The config passed in or taken from the ambient context.
IsValid bool false once disposed.
IsApplied bool Whether the hook is currently in its chain.
DetourInfo DetourInfo Introspection object for this hook. See Introspection.

Errors

Exception Message When
ArgumentNullException — source, target, or factory is null.
ArgumentException Source method is generic, generic hooks are not supported The source is a generic method, or a method on a generic type.
ArgumentException Target method is nonstatic, but no target object was provided Instance MethodInfo target without targetObj.
ArgumentException Target method is static, but a target object was provided Static target with a non-null targetObj.
ArgumentException Target method is not compatible with source method Parameters or return types do not match by the rules above.
ArgumentException Target method's delegate parameter is not compatible with the source method The orig delegate's Invoke signature does not match the source.
InvalidOperationException Could not get Invoke method of delegate A multicast delegate type without an Invoke method (should not happen with normal delegate types).
ObjectDisposedException — Apply()/Undo() after Dispose().

Notes and Pitfalls

  • Inlining. If the JIT inlined the source into a caller before you hooked it, that caller keeps running the old code. Mark methods you control with [MethodImpl(MethodImplOptions.NoInlining)]. For third-party code, hook early or hook the caller instead. See Troubleshooting.
  • Hooks are per method, not per call site. Hooking a virtual method hooks that specific implementation; overrides in derived classes are separate methods.
  • Many hooks, one chain. Hooks from different mods on the same method are stacked in one chain. Hooks without a DetourConfig run after all configured hooks and behave like a stack: the most recently applied one runs first (see Detour Order).
  • Hooks may add or remove hooks (even themselves) while running. See Hot patching.
  • Generic code: hook a non-generic caller or helper instead, or use an ILHook on a non-generic method that calls the generic one.

See Also