0

I've been trying to approach this issue for a while now and I have not been able to find an answer. Basically, I have a certain method that, when called, actually executes another different method rather than the method itself which I assume needs me to modify to where the method's pointer is pointing.

Say this,

public class A : OtherRandomClass
{
   protected void SomeMethod()
   {
     //code
   }
}

public class B
{
   public void OtherMethod()
   {
     //code that I want to execute when SomeMethod is called
   }
}

I cannot modify class A's source unfortunately, but what I want to try to do is to make any calls to SomeMethod actually invoke OtherMethod while preventing SomeMethod itself from being invoked, I don't want to resort to swapping method bodies.

I am aware of just how much bad practice this is, but the framework I'm using is just plain stupid and I have no other choice.

Any approaches to this?

Edit: Found what I was looking for, thanks to anyone who attempted to help!

Trivaxy
  • 41
  • 1
  • 5
  • 3
    Are all of the *call sites* for `SomeMethod` in code you control, or is that also not modifiable? Also, your example methods are instance methods and `A` and `B` don't appear to have any inheritance relationship - where is the `B` instance to be conjured from during such a call? – Damien_The_Unbeliever Jun 19 '17 at 10:37
  • Is https://stackoverflow.com/questions/25366243/intercept-method-calls of use? – mjwills Jun 19 '17 at 10:40
  • @Damien_The_Unbeliever Can't really control any of the sites that call SomeMethod. A and B are totally separate classes not related to each other in terms of inheritance. The `B` instance would be instantiated after `A`. Also, @mjwills, I'll have to look into that more but it doesn't seem like it. – Trivaxy Jun 19 '17 at 10:49
  • **Why?** is the million dollar question here. Why not just call the other method yourself? – Clint Jun 19 '17 at 12:48
  • @Clint I can call it myself, but it's the location of the call I'm concerned about. Either way, I found what I was looking for. – Trivaxy Jun 19 '17 at 13:00
  • What solution did you find @Trivaxy ? – mjwills Jun 19 '17 at 13:18

1 Answers1

0

This doesn't look simple, and to be perfectly honest, I never attempted to do such a thing.

I'd really like to know your context, because if what you want to do was my last option, I would not work with this assembly.

This answer suggests replacing the loaded method body (which is written then in Intermediate Language) with your own, by using reflection:

You can use MethodInfo.GetMethodBody().GetILAsByteArray(), modify that, and then plug it back into MethodBuilder.CreateMethodBody().

You can then check this question and its answers to have a rough idea of how you should implement it all, but it looks like CreateMethodBody isn't fully supported and could have some unexpected behavior.

Overall, it's pretty complicated and doesn't look worth the hassle.

Kilazur
  • 3,089
  • 1
  • 22
  • 48