Skip to content

Custom MethodPatcher

Geoffrey Horsington edited this page Mar 20, 2021 · 2 revisions

The core benefit of HarmonyX is the ability to extend the patching backend to support patching alternative methods. This allows to use Harmony's attribute-based patching on methods that are not managed by default.

Some use cases for specifying the custom patching backend:

  • Ability to patch mono internal calls and DllImport methods. A basic implementation already exists in HarmonyX: NativeDetourMethodPatcher
  • Ability to patch Il2Cpp methods like managed methods. An example implementation with Il2CppUnhollower: IL2CPPDetourMethodPatcher

Basic usage

To implement a custom method patcher:

  1. Create a new class that inherits MethodPatcher and implement the required methods. Refer to the documentation that explains each method in detail. In addition, refer to two example implementations:

  2. Implement a resolver method. This is a simple static method with the following signature:

    public static void TryResolve(object sender, PatchManager.PatcherResolverEventArgs args)
    {
    }

    The method will be called by HarmonyX when a method is to be patched. The resolver should check the method passed in the args and initialize the instance of the custom MethodPatcher if there is a match. In most cases the body of TryResolve is:

    if (/* some logic to check if args.Original should be patched with the custom patcher */)
        args.MethodPatcher = new MyCustomMethodPatcher(args.Original);
  3. Register your resolver with PatchManager.ResolvePatcher event. You simply register your resolver as an event handler before applying your patches:

    PatchManager.ResolvePatcher += TryResolve;