3

I have to augment some methods in a closed source library. I was searching for some really simple way to swap implementations of two static methods (with entirely the same signature).

I found MethodRental.SwapMethodBody, which I really like, but without deeper knowledge of the underlying runtime, I'm almost just guessing how to use it.

Can someone fix up this code below? Or suggest an entirely different approach?

using System;
using System.Reflection;
using System.Reflection.Emit;

public class Example
{
    // This should be replaced (swapped)...
    static string OriginalMethod(string a, string b)
    { return string.Format("a={0}; b={1};", a, b); }

    // ...with this.
    static string NewMethod(string a, string b)
    { return string.Format("`a` is `{0}` and b is `{1}`.", a, b); }

    void Swap()
    {
        System.Type type = typeof(Example);

        // Original.
        MethodInfo originalMethod = type.GetMethod("OriginalMethod");
        MethodToken originalMethodToken = // How to obtain this ???

        // New.
        MethodInfo newMethod = type.GetMethod("NewMethod");
        IntPtr newMethodPointer = newMethod.MethodHandle.GetFunctionPointer();
        int methodByteSize = newMethod.GetMethodBody().GetILAsByteArray().Length;

        // Swap.
        MethodRental.SwapMethodBody(
            type, 
            originalMethodToken.Token, 
            newMethodPointer,
            methodByteSize,
            MethodRental.JitImmediate); 
    }
}
Geri Borbás
  • 15,810
  • 18
  • 109
  • 172
  • Interesting... I've never used this before, but MethodInfo has a MetadataToken property, which is just an integer. – Mike Zboray Mar 11 '16 at 01:05
  • I'm afraid it works only with a dynamic module (whatever it is). Written here https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/reflection/emit/methodrental.cs at the class summary comment. – Geri Borbás Mar 11 '16 at 01:08
  • @mije z Hmm... ...what about this https://ubbecode.wordpress.com/2014/05/05/updating-method-at-runtime-native/ article? It clearly suggests this method at the end. – Geri Borbás Mar 11 '16 at 01:17
  • 1
    The [docs](https://msdn.microsoft.com/en-us/library/system.reflection.emit.methodrental.swapmethodbody(v=vs.110).aspx) say it only applies to dynamic methods: "The method can only be called by the client that created the dynamic module that contains the type whose method's body is being swapped.", so I'm not surprised it doesn't work. – Mike Zboray Mar 11 '16 at 01:22
  • Any other chance to do such things? – Geri Borbás Mar 11 '16 at 01:33
  • 1
    This probably can help: http://www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-time – Diligent Key Presser Mar 11 '16 at 01:37

0 Answers0