DynamicMethodDefinition
MonoMod.Utils.DynamicMethodDefinition (often shortened to DMD) represents a method as an editable Mono.Cecil MethodDefinition and turns it into a callable MethodInfo. MonoMod uses it everywhere: to copy the IL of a method that is about to be detoured, to build hook proxies and trampolines, and to apply ILHook changes. You can use it directly to clone a method's IL, edit it, and generate a new method, or to build a method from scratch with Cecil or with a System.Reflection.Emit-style ILGenerator.
Constructors
| Constructor | Description |
|---|---|
DynamicMethodDefinition(MethodBase method) |
Loads the IL of an existing method into a new definition. OriginalMethod is set to method. |
DynamicMethodDefinition(DynamicMethodDefinition method) |
Copies another DMD. OriginalMethod is null; Name is copied. |
DynamicMethodDefinition(string name, Type? returnType, Type[] parameterTypes) |
Creates an empty static method with that signature. A null return type means void. |
All three throw ArgumentNullException for null required arguments.
Members
| Member | Type | Description |
|---|---|---|
Definition |
MethodDefinition |
The Cecil method you edit. |
Module |
ModuleDefinition |
The temporary module that holds it. |
OriginalMethod |
MethodBase? |
The method this DMD was loaded from, if any. |
Name |
string? |
The name given to the from-scratch or copy constructors. |
Debug |
bool (init) |
Emit debug information when the backend supports it; also changes backend selection. Defaults to the DMDDebug switch. |
IsAsync |
bool |
Gets or sets the runtime-async implementation flag on Definition. Setting it to true asserts that runtime async is supported. |
IsDynamicILAvailable |
static bool |
false when MonoMod detected that System.Reflection.Emit's dynamic IL support is stubbed out on this runtime (and therefore prefers Cecil). |
GetILProcessor() |
ILProcessor |
Cecil IL processor for Definition. |
GetILGenerator() |
ILGenerator |
A System.Reflection.Emit.ILGenerator-compatible shim that writes into Definition. |
Generate() / Generate(object? context) |
MethodInfo |
Compiles the definition with a backend and returns a callable method. |
GetDumpName(string type) |
string |
The name used for dumped assemblies, DMDASM.<hash>[.<type>]. |
Dispose() |
Disposes the Cecil module. |
Example: Clone and Modify a Method
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.Utils;
MethodInfo original = typeof(Player).GetMethod("TakeDamage")!;
using var dmd = new DynamicMethodDefinition(original);
// Edit with an ILCursor...
new ILContext(dmd.Definition).Invoke(il =>
{
var c = new ILCursor(il);
c.GotoNext(MoveType.After, i => i.MatchLdarg(1));
c.EmitLdcI4(0);
c.EmitMul(); // damage * 0
});
MethodInfo patched = dmd.Generate();
// The generated method is static: an instance method's `this` becomes the first parameter.
int health = (int)patched.Invoke(null, new object[] { new Player(), 40 })!; // 100
The generated method is a new method. It does not replace original; to make calls to original run new code, use a Hook or ILHook.
Example: Build a Method From Scratch
using var dmd = new DynamicMethodDefinition("AddOne", typeof(int), new[] { typeof(int) });
var il = dmd.GetILGenerator(); // familiar Reflection.Emit API
il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_1);
il.Emit(System.Reflection.Emit.OpCodes.Add);
il.Emit(System.Reflection.Emit.OpCodes.Ret);
var addOne = dmd.Generate().CreateDelegate<Func<int, int>>();
Console.WriteLine(addOne(41)); // 42
CreateDelegate<T>() here is the extension method from MonoMod.Utils; on modern runtimes MethodInfo.CreateDelegate<T>() works too.
Backends
Generate() turns the Cecil definition into a real method using one of three backends ("generators"):
| Backend | Switch values | How it works | Notes |
|---|---|---|---|
DynamicMethod |
dynamicmethod, dm |
Emits a System.Reflection.Emit.DynamicMethod. |
Usually the default. No dumps. |
| Cecil | cecil, md |
Writes a small assembly with Cecil and loads it from a byte array. | The most portable, and the final fallback. Every DMD loads a new module, which adds metadata bloat. |
MethodBuilder |
methodbuilder, mb |
Uses TypeBuilder/MethodBuilder in a dynamic assembly. |
Only compiled into the .NET Framework and net9.0+ builds of MonoMod.Utils. |
Selection Order
Generate() decides as follows (from DynamicMethodDefinition.cs):
- If the
DMDTypeswitch is set to one of the names above, that backend is used. Any other value is treated as the full name of a custom generator type (a subclass ofDMDGenerator<TSelf>), which is instantiated once and cached. If the named type exists but is not a generator, an error is logged and the default selection continues. If the method is runtime-async and the chosen backend does not support async methods, an error is logged and the default selection continues. - If dynamic IL is unavailable on this runtime (
IsDynamicILAvailableisfalse), Cecil is tried first. - If
Debugistrue:MethodBuilderis tried in builds that support it; otherwise Cecil. - On .NET Framework builds, if the method has
faultorfilterexception blocks (whichDynamicMethoddoes not support there),MethodBuilderis tried. DynamicMethodis tried.MethodBuilderis tried, in builds that have it.- Cecil is used as the last resort.
Each backend is tried at most once per call, and a backend that does not support runtime-async methods is skipped for async methods.
Note: A
DMDTypevalue that is neither a built-in name nor a resolvable type name is silently ignored: no error is logged and the default selection is used.
Dumping Generated Methods
Set the DMDDumpTo switch to a directory to have generated methods written to disk as assemblies, which you can open in a decompiler. Only the Cecil and MethodBuilder backends dump; DynamicMethod cannot. Combine it with DMDDebug so that a dumping backend is selected:
MONOMOD_DMDDebug=1 MONOMOD_DMDDumpTo=/tmp/mmdump dotnet run