Emit local variable which is not a standard type and assign a value to it

73 views Asked by At

We can assign a variable using EMIT which has a standard type such as string, etc. But how can I assign a non-standard type such as Type?

        DynamicMethod dynamicMethod
            = new DynamicMethod("test",null,null);
        var il = dynamicMethod.GetILGenerator();
        Type types = typeof(StringBuilder);
        LocalBuilder ilType= il.DeclareLocal(typeof(Type));
        il.Emit(OpCodes.Ldloc,types);
        il.Emit(OpCodes.Stloc,ilType);
        il.Emit(OpCodes.Ldloc,ilType);
        il.Emit(OpCodes.Call,typeof(Console).GetMethod("WriteLine",new[]{typeof(object)})!);
        il.Emit(OpCodes.Ret);
        dynamicMethod.CreateDelegate(typeof(Action)).DynamicInvoke();

the error output:

Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
   at test()
   --- End of inner exception stack trace ---

And I want to find a function which I can compile and decompile it to find its IL. But I cannot find such a function.
Can you solve this question using this method?

0

There are 0 answers