title: How to inject IL into a method at runtime
body: <p>Title more or less says it all. Based on <a href="http://www.codeproject.com/KB/dotnet/CLRMethodInjection.aspx" rel="noreferrer">this</a> article, I've come up with this:</p>
  
  <pre><code>public static unsafe void Replace(this MethodBase destination, MethodBase source)
  {
      IntPtr srcHandle = source.MethodHandle.GetFunctionPointer();
      IntPtr dstHandle = destination.MethodHandle.GetFunctionPointer();
  
      int* dstPtr = (int*)dstHandle.ToPointer();
      *dstPtr = srcHandle.ToInt32();
  }
  </code></pre>
  
  <p>This actually works... occasionally -.-</p>
  
  <p>For example, this works.</p>
  
  <pre><code>public static class Program
  {
      public static void Main(string[] args)
      {
          MethodInfo methodA = typeof(Program).GetMethod("A", BindingFlags.Public | BindingFlags.Static);
          MethodInfo methodB = typeof(Program).GetMethod("B", BindingFlags.Public | BindingFlags.Static);
  
          methodA.Replace(methodB);
  
          A();
          B();
      }
  
      public static void A()
      {
          Console.WriteLine("Hai World");
      }
  
      public static void B()
      {
          Console.WriteLine("Bai World");
      }
  }
  </code></pre>
  
  <p>However, this doesn't (SEHException). All I did was change the order in which the functions were defined.</p>
  
  <pre><code>public static class Program
  {
      public static void Main(string[] args)
      {
          MethodInfo methodA = typeof(Program).GetMethod("A", BindingFlags.Public | BindingFlags.Static);
          MethodInfo methodB = typeof(Program).GetMethod("B", BindingFlags.Public | BindingFlags.Static);
  
          methodA.Replace(methodB);
  
          A();
          B();
      }
  
      public static void B()
      {
          Console.WriteLine("Bai World");
      }
  
      public static void A()
      {
          Console.WriteLine("Hai World");
      }
  }
  </code></pre>
  
  <p>As for the code in the article... I couldn't get it to work at all.</p>
  
  <p>Any ideas/alternatives?</p>