pepoluan
pepoluan

Reputation: 6780

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

Upvotes: 4

Views: 3220

Answers (2)

Nirmal
Nirmal

Reputation: 41

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();
}

Upvotes: 4

Basit Anwer
Basit Anwer

Reputation: 6870

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 );

Upvotes: 4

Related Questions