Search code examples
c#reflection.emitil

Create DynamicMethod to assign value to a property?


This is a learning exercise. I created a method that takes a Foo and a string and sets the A property. I used the Reflector disassembly to make the following emit code. The disassembly looks like this:

.method private hidebysig static void Spork(class ConsoleTesting.Foo f, string 'value') cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: callvirt instance void ConsoleTesting.Foo::set_A(string)
    L_0007: ret 
}

Ok, so I modeled my emit code after that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;


namespace ConsoleTesting
{
    class Foo
    {
        public string A { get; set; }
    }

    class Program
    {
        static Action<Foo, string> GenMethodAssignment(string propName)
        {
            MethodInfo setMethod = typeof(Foo).GetMethod("get_" + propName);
            if (setMethod == null)
                throw new InvalidOperationException("no property setter available");

            Type[] argTypes = new Type[] { typeof(Foo), typeof(String) };
            DynamicMethod method = new DynamicMethod("__dynamicMethod_Set_" + propName, null, argTypes, typeof(Program));
            ILGenerator IL = method.GetILGenerator();
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg_1);
            IL.Emit(OpCodes.Callvirt, setMethod);
            IL.Emit(OpCodes.Ret);
            method.DefineParameter(1, ParameterAttributes.In, "instance");
            method.DefineParameter(2, ParameterAttributes.In, "value");

            Action<Foo, string> retval = (Action<Foo, string>)method.CreateDelegate(typeof(Action<Foo, string>));
            return retval;
        }

        static void Main(string[] args)
        {
            Foo f = new Foo();
            var meth = GenMethodAssignment("A");
            meth(f, "jason");
            Console.ReadLine();
        }
    }

I'm getting this exception:

JIT Compiler encountered an internal limitation.

What the krunk does that mean, and how do I fix it?

EDIT:

I thought maybe it's because the target method is private, but I'm not so sure. From the DynamicMethod MSDN page:

The following code example creates a DynamicMethod that is logically associated with a type. This association gives it access to the private members of that type.


Solution

  • Well I figured it out. Changing

    IL.Emit(OpCodes.Callvirt, setMethod);
    

    to

    IL.Emit(OpCodes.Call, setMethod);
    

    fixed it. I don't know why the disassembly showed CallVirt, but eh.