I'm just curious on how I would call a method on a field using Emit
.
I have this class generated
public class AClass : IDynamicProxyTestInterface
{
private DynamicProxy<IDynamicProxyTestInterface> proxy;
public AClass(DynamicProxy<IDynamicProxyTestInterface> p)
{
proxy = p;
}
public void Hello()
{
// Here I want to do the following
Int32 code = 123456;
proxy.HandleCall(code);
}
}
The commented part is what I've been struggling to figure out.
I have this code(commented out stuff is stuff I've been turning on and off, trying to make it work)
var methodBuilder = typeBuilder.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
methodInfo.ReturnType,
methodInfo.GetParameters().Select(p => p.GetType()).ToArray()
);
var methodIlGen = methodBuilder.GetILGenerator();
// Add proxy call to method
var emptyAction = new DynamicProxyOnBuilder();
ProxyCalls.Add(methodInfo.GetHashCode(), emptyAction);
// Drop method info hash into local variable 0
//var hash = methodInfo.GetHashCode();
//methodIlGen.Emit(OpCodes.Ldc_I4, hash);
//methodIlGen.DeclareLocal(typeof(Int32), false);
//methodIlGen.Emit(OpCodes.Stloc_0);
// Create local variable for instance of this DynamicProxy
methodIlGen.Emit(OpCodes.Ldarg_0);
methodIlGen.Emit(OpCodes.Ldflda, proxyField);
var var2 = methodIlGen.DeclareLocal(this.GetType());
methodIlGen.Emit(OpCodes.Stloc,var2);
////methodIlGen.EmitWriteLine(proxyField);
////methodIlGen.Emit(OpCodes.St);
//methodIlGen.Emit(OpCodes.Ldloc,var2);
methodIlGen.Emit(OpCodes.Call, this.GetType().GetMethods().First(x => x.Name == "HandleCall"));
Any ideas what I'm doing wrong here?
BTW the errors that I get are
Common Language Runtime detected an invalid program.
and JIT Compiler encountered an internal limitation.