CSharp · Console
using System;
using System.Reflection;
using System.Reflection.Emit;
public class Program
{
public static void Main(string[] args)
{
var method = GetDM();
var result = method.Invoke(null, new Object[]{"Test 1234", true});
Console.WriteLine(result); // Should be 2
}
public static int Test(Object[] args)
{
Console.WriteLine(args.Length);
return args.Length;
}
public static DynamicMethod GetDM() {
var returnType = typeof(int);
var paramTypes = new Type[]{typeof(string), typeof(bool)};
var method = new DynamicMethod(
"",
returnType,
paramTypes,
false
);
var il = method.GetILGenerator();
// Save parameters in an object array
il.Emit(OpCodes.Ldc_I4_S, paramTypes.Length);
il.Emit(OpCodes.Newarr, typeof(Object));
il.Emit(OpCodes.Dup);
for (int i = 0; i < paramTypes.Length; i++)
{
Type type = paramTypes[i];
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i);
if (type.IsValueType) { il.Emit(OpCodes.Box, type); }
il.Emit(OpCodes.Stelem_Ref);
il.Emit(OpCodes.Dup);
}
// Call method and get the length of the array
// How do I return the result of the called method?
var callMethod = typeof(Program).GetMethod("Test", (BindingFlags)(-1));
il.Emit(OpCodes.Call, callMethod);
il.Emit(OpCodes.Ret);
return method;
}
}