Custom MethodPatcher - BepInEx/HarmonyX GitHub Wiki
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:
-
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:ManagedMethodPatcher
(patched normal managed methods);NativeDetourMethodPatcher
(patches icalls and DllImports)
-
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 customMethodPatcher
if there is a match. In most cases the body ofTryResolve
is:if (/* some logic to check if args.Original should be patched with the custom patcher */) args.MethodPatcher = new MyCustomMethodPatcher(args.Original);
-
Register your resolver with
PatchManager.ResolvePatcher
event. You simply register your resolver as an event handler before applying your patches:PatchManager.ResolvePatcher += TryResolve;