Dynamically replace the contents of a C# method?

后端 未结 10 2312
面向向阳花
面向向阳花 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:37

    you can replace it if the method is non virtual, non generic, not in generic type, not inlined and on x86 plateform:

    MethodInfo methodToReplace = ...
    RuntimeHelpers.PrepareMetod(methodToReplace.MethodHandle);
    
    var getDynamicHandle = Delegate.CreateDelegate(Metadata>.Type, Metadata.Type.GetMethod("GetMethodDescriptor", BindingFlags.Instance | BindingFlags.NonPublic)) as Func;
    
    var newMethod = new DynamicMethod(...);
    var body = newMethod.GetILGenerator();
    body.Emit(...) // do what you want.
    body.Emit(OpCodes.jmp, methodToReplace);
    body.Emit(OpCodes.ret);
    
    var handle = getDynamicHandle(newMethod);
    RuntimeHelpers.PrepareMethod(handle);
    
    *((int*)new IntPtr(((int*)methodToReplace.MethodHandle.Value.ToPointer() + 2)).ToPointer()) = handle.GetFunctionPointer().ToInt32();
    
    //all call on methodToReplace redirect to newMethod and methodToReplace is called in newMethod and you can continue to debug it, enjoy.
    

提交回复
热议问题