Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a 'normal' method through ILGenerator.Emit*?

Is it possible for a DynamicMethod to call (via ILGenerator.EmitCall -- or similar -- for instance) a 'normal' method, e.g. Private Sub BlahBlah(ByVal obj as Object)?

Thanks in advance

like image 767
pepoluan Avatar asked Feb 25 '23 07:02

pepoluan


2 Answers

Load values on evaluation stack to be given to the method

MethodInfo methodInfo = typeof(ClassName).GetMethod(MethodName, new Type[1] { typeof(-method argument types-) });

IL.Emit(OpCodes.Call, methodInfo );
like image 112
Basit Anwer Avatar answered Feb 26 '23 21:02

Basit Anwer


delegate void foo();

public static void show(string foo)
{
    MessageBox.Show(foo);
}

public void test()
{
    DynamicMethod dm = new DynamicMethod("foo", null, null);
    ILGenerator gen = dm.GetILGenerator();
    gen.Emit(OpCodes.Ldstr, "hello world");
    gen.EmitCall(OpCodes.Call, this.GetType().GetMethod("show"),null);
    gen.Emit(OpCodes.Ret);
    var b = dm.CreateDelegate(typeof(foo)) as foo;
    b();
}
like image 32
Nirmal Avatar answered Feb 26 '23 19:02

Nirmal