A purely sporting interest appeared for the sake of the problem: during RunTime replace the body of one method with the body of another. Actually, the task was successfully, as it seemed at first glance, solved in this way:

 public static void Inject(MethodInfo ToReplace, MethodInfo ToInject) { RuntimeHelpers.PrepareMethod(ToReplace.MethodHandle); RuntimeHelpers.PrepareMethod(ToInject.MethodHandle); unsafe { byte* inject = (byte*)(IntPtr.Size == 4 ? *((int*)ToInject.MethodHandle.Value.ToPointer() + 2) : *((long*)ToInject.MethodHandle.Value.ToPointer() + 1)); byte* target = (byte*)(IntPtr.Size == 4 ? *((int*)ToReplace.MethodHandle.Value.ToPointer() + 2) : *((long*)ToReplace.MethodHandle.Value.ToPointer() + 1)); int* injectSrc = (int*)(inject + 1); int* targetSrc = (int*)(target + 1); *targetSrc = (((int)inject + 5) + *injectSrc) - ((int)target + 5); } } 

I prepare the methods for inclusion in the restricted execution area, and then I simply replace the pointer to the body of the ToReplace method ToReplace pointer to the body of the ToInject method.

This works fine, but only in Debug mode, when no optimizations are applied. So my question is: what are some other ways to replace methods during execution?

Ps . - the question is purely for general development, and not for some serious and reliable things, so the most unsafe options are also welcome)

  • there is a similar code , it says for the release :-) - Grundy
  • @Grundy however still does not work) - Kir_Antipov pm
  • maybe it's a matter of bias :) - Grundy

0