Dynamically replace the contents of a C# method?

后端 未结 10 2297
面向向阳花
面向向阳花 2020-11-22 16:09

What I want to do is change how a C# method executes when it is called, so that I can write something like this:

[Distributed]
public DTask Solve         


        
10条回答
  •  无人及你
    2020-11-22 16:31

    have a look into Mono.Cecil:

    using Mono.Cecil;
    using Mono.Cecil.Inject;
    
    public class Patcher
    {    
       public void Patch()
       {
        // Load the assembly that contains the hook method
        AssemblyDefinition hookAssembly = AssemblyLoader.LoadAssembly("MyHookAssembly.dll");
        // Load the assembly
        AssemblyDefinition targetAssembly = AssemblyLoader.LoadAssembly("TargetAssembly.dll");
    
        // Get the method definition for the injection definition
        MethodDefinition myHook = hookAssembly.MainModule.GetType("HookNamespace.MyHookClass").GetMethod("MyHook");
        // Get the method definition for the injection target. 
        // Note that in this example class Bar is in the global namespace (no namespace), which is why we don't specify the namespace.
        MethodDefinition foo = targetAssembly.MainModule.GetType("Bar").GetMethod("Foo");
    
        // Create the injector
        InjectionDefinition injector = new InjectionDefinition(foo, myHook, InjectFlags.PassInvokingInstance | InjectFlags.passParametersVal);
    
        // Perform the injection with default settings (inject into the beginning before the first instruction)
        injector.Inject();
    
        // More injections or saving the target assembly...
       }
    }
    

提交回复
热议问题