Reflection.Emit for dynamic method creation

I would like to create dynamically some method that will take a single parameter - an instance of class A, and then execute method B on the passed instance A. B has a parameter of type int. So here's the diagram:

dynamicMethod(A a){
a.B(12);
}

      

Here's what I've tried:

DynamicMethod method = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(A) }, typeof(Program));
MethodInfo methodB = typeof(A).GetMethod("B", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
ILGenerator gen = method.GetILGenerator();

gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_S, 100);
gen.Emit(OpCodes.Call, methodB);

      

But the compiler tells me the CLR didn't find the method. could you help me?

+2


source to share


1 answer


MSDN about the types parameter of the Type.GetMethod function :

An array of type objects representing the number, order, and type of parameters for the method.

You are passing in an empty array that indicates "a method that takes no parameters". But as you said, "B has [a] an int parameter."

This will work:

MethodInfo methodB = typeof(A).GetMethod(
            "B",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
            null,
            new Type[] { typeof(int) }
            , null);

      




If I understand correctly, it Ldarg_S

will load one hundredth argument of your method, similar to Ldarg_0:

gen.Emit(OpCodes.Ldarg_S, 100);

      

Use Ldc_I4 to load the constant value

gen.Emit(OpCodes.Ldc_I4, 100);

      

+1


source







All Articles