You should use OpCodes.Ldarg_0
instead of OpCodes.Ldarg_1
to get first method argument.
"Operation could destabilize the runtime" when calling dynamic method
-
23-06-2023 - |
Frage
I am trying to right a Func that I can use to access the get method of a property, but have hit a stumbling block.
The dynamic method below is created fine, however when it is invoked I get the following error.
VerificationException, Operation could destabilize the runtime.
I have checked that the il code emits a valid function by writing it to a class rather than a dynamic method and all would appear to be fine.
I'm guessing it has to do with some typing issue but I'm not sure where, so any help is appreciated.
Example class
public class DemoClass
{
public string Property{get;set;}
}
Dynamic method creation
var getMethods = new DynamicMethod(string.Empty,
typeof(string),
new Type[] {typeof(object) });
var ilGet = getMethods.GetILGenerator();
var falseGetLabel = ilGet.DefineLabel();
ilGet.Emit(OpCodes.Ldarg_1);
ilGet.Emit(OpCodes.Isinst, typeof(DemoClass));
ilGet.Emit(OpCodes.Brfalse_S, falseGetLabel);
ilGet.Emit(OpCodes.Ldarg_1);
ilGet.Emit(OpCodes.Isinst, typeof(DemoClass));
ilGet.Emit(OpCodes.Call, typeof(DemoClass).GetProperty("Property").GetMethod);
ilGet.Emit(OpCodes.Ret);
ilGet.MarkLabel(falseGetLabel);
ilGet.Emit(OpCodes.Newobj,
typeof(InvalidOperationException).GetConstructor(Type.EmptyTypes));
ilGet.Emit(OpCodes.Throw);
var f = (Func<object,string>)getMethods.CreateDelegate(
typeof(Func<object,string>));
var x = new DemoClass{Property = "9"};
Console.WriteLine(f(x)); <--- fails here
Lösung
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow