I am figuring out Reflection.Emit for some internal libraries and got stuck with calling a Func passed in as an argument. My scenario test uses the code transferred to IL with Linqpad in the picture
My code to duplicate the IL in a DynamicMethod is the following
public class ScopeTest
{
public delegate Task WrapScope(Func<Task> value);
public (WrapScope scope,string id) WrapScopeInId()
{
var id = $"wrap~{Guid.NewGuid().ToString().Replace("-",string.Empty)}";
var mi = typeof(Func<Task>).GetMethod("Invoke");
var d = new DynamicMethod(id, typeof(Task), new[] { typeof(Func<Task>) });
var gen = d.GetILGenerator();
var lab = gen.DefineLabel();
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, mi);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Br_S, lab);
gen.MarkLabel(lab);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ret);
WrapScope del = (WrapScope)d.CreateDelegate(typeof(WrapScope));
return (del,id);
}
}
The code compiles and returns but when you call the WrapScope delegate del(Func<Task>)
it throws a System.InvalidProgramException: Common Language Runtime detected an invalid program.
What could be the problem running this DynamicMethod?
Thanks