我想使用reflection.emit
API调用带有参数的函数。以下是我目前所拥有的。但是,当我运行它时,它将引发以下异常:System.InvalidProgramException : Common Language Runtime detected an invalid program
。所以我的问题是我下面的代码片段有什么错误?有人可以帮我吗?
public class Test
{
public void test()
{
Func<int, long> realSquareFunc = (val) => val * val;
Type[] methodArgs = { typeof(int) };
DynamicMethod squareIt = new DynamicMethod(
"SquareIt",
typeof(long),
methodArgs,
typeof(Test).Module)
;
ILGenerator il = squareIt.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Save parameter on stack
il.Emit(OpCodes.Call, realSquareFunc.Method); // Call function with input as parameter
il.Emit(OpCodes.Ret); // Return value from function call before
var myMethod = (Func<int, long>)squareIt.CreateDelegate(realSquareFunc.GetType());
var result = myMethod.Invoke(4); // Should be 16 (4*4)
}
}
如果被调用的方法是静态方法,您的代码将按原样工作:
public static long RealSquare(int val) => val * val;
public void test()
{
Func<int, long> realSquareFunc = RealSquare;
// ...
但是,realSquareFunc = (val) => val * val
lambda实际上被编译为隐藏类的实例方法。要调用实例方法,必须在方法参数之前先将实例推入堆栈。实例方法调用通常也使用Callvirt
操作码(无论它们是否是虚拟的,因为此操作码都会执行空引用检查):
public class Test
{
public long RealSquare(int val) => val * val;
public void test()
{
Func<int, long> realSquareFunc = RealSquare;
// pass the instance we want to call the method on in as well
Type[] methodArgs = { typeof(Test), typeof(int) };
DynamicMethod squareIt = new DynamicMethod(
"SquareIt",
typeof(long),
methodArgs,
typeof(Test).Module)
;
ILGenerator il = squareIt.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Push the target instance onto stack
il.Emit(OpCodes.Ldarg_1); // Save parameter on stack
il.Emit(OpCodes.Callvirt, realSquareFunc.Method); // Call function with input as parameter
il.Emit(OpCodes.Ret); // Return value from function call before
var myMethod = (Func<Test, int, long>)squareIt.CreateDelegate(typeof(Func<Test, int, long>));
var result = myMethod.Invoke(this, 4); // Should be 16 (4*4)
}
}
由于涉及到编译器生成的类,因此调用lambda direct的目标方法更为复杂,但是如果您要调用一个委托,它通常是这样的:
public class Test
{
public void test()
{
Func<int, long> realSquareFunc = (val) => val * val;
// pass the delegate we want to call into the method
Type[] methodArgs = { realSquareFunc.GetType(), typeof(int) };
DynamicMethod squareIt = new DynamicMethod(
"SquareIt",
typeof(long),
methodArgs,
typeof(Test).Module)
;
ILGenerator il = squareIt.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Push the delegate onto stack
il.Emit(OpCodes.Ldarg_1); // Save parameter on stack
il.Emit(OpCodes.Callvirt, realSquareFunc.GetType().GetMethod("Invoke")); // Invoke delegate
il.Emit(OpCodes.Ret); // Return value from function call before
var myMethod = (Func<Func<int, long>, int, long>)squareIt
.CreateDelegate(typeof(Func<Func<int, long>, int, long>));
var result = myMethod.Invoke(realSquareFunc, 4); // Should be 16 (4*4)
}
}