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);
}
}