using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static void Main()
ExternalClass.Initialize();
public static int Somar(int a, int b){
public static int Subtrair(int a, int b){
static class ExternalClass
public static void Initialize()
MethodInfo methodFrom = typeof(Program).GetMethod("Somar");
MethodInfo methodTo = typeof(Program).GetMethod("Subtrair");
ReplaceMethodCall(methodFrom, methodTo);
private static void ReplaceMethodCall(MethodInfo from, MethodInfo target)
RuntimeHelpers.PrepareMethod(from.MethodHandle);
RuntimeHelpers.PrepareMethod(target.MethodHandle);
long fromPointer = from.MethodHandle.GetFunctionPointer().ToInt64();
long targetPointer = target.MethodHandle.GetFunctionPointer().ToInt64();
WriteBytes(ref fromPointer, new byte[] { 0x48, 0xB8 });
WriteLong(ref fromPointer, targetPointer);
WriteBytes(ref fromPointer, new byte[] { 0xFF, 0xE0 });
private static void WriteBytes(ref long address, byte[] bytes)
foreach (byte b in bytes)
Marshal.WriteByte(new IntPtr(address), b);
private static void WriteLong(ref long address, long value)
Marshal.WriteInt64(new IntPtr(address), value);