6

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.

  • You're accessing the "get_" method; is this just a typo in your post? Note that you can access the property by name and use the GetSetMethod() method on the PropertyInfo object; this way you're not relying on the C# convention of "get_" and "set_". – Dan Bryant Jan 03 '11 at 22:03
  • I did, however, correct a typo just now. The IL contained AStr, instead of A, because I had renamed the property for the purposes of this post. –  Jan 03 '11 at 22:11
  • Ah, I misinterpreted the first sentence of your comment. You're absolutely right. –  Jan 03 '11 at 22:26
  • I don't think the target is private, since it looks like a public property to me. However, you have to associate the DynamicMethod with the right class, currently it has access to private methods of `Program` and not of `Foo`. – Ben Voigt Jan 03 '11 at 23:52

3 Answers3

4

Interesting issue. First there are few things you can do. If you only want a delegate for the setter you can use Delegate.CreateDelegate.

Delegate.CreateDelegate(typeof(Action<Foo, string>),typeof(Foo).GetProperty("A").GetSetMethod()) as Action<Foo,String>;

If you are using .NET 3.5+ you can use expression trees and I strongly recommend learning them over DynamicMethod, they have limited use in .NET 3.5 and almost none .NET 4. (TypeBuilder is still very useful though).

var targetExpression = Expression.Parameter(typeof(Foo),"target");
var valueExpression = Expression.Parameter(typeof(string),"value");
var expression = Expression.Lambda<Action<Foo,string>>(
      Expression.Call(
           targetExpression, 
           typeof(Foo).GetProperty("A").GetSetMethod(),
           valueExpression
      ),
      targetExpression,
      valueExpression
);

In .NET 4 you can write it to be slightly prettier by using Expression.Assign, but it's not much better.

Finally, if you really want to do it in IL this works.

        DynamicMethod method = new DynamicMethod("Setter", typeof(void), new[] { typeof(Foo), typeof(string) }, true);
        var ilgen = method.GetILGenerator();
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Ldarg_1);
        ilgen.Emit(OpCodes.Callvirt, typeof(Foo).GetProperty("A").GetSetMethod());
        ilgen.Emit(OpCodes.Ret);
        var action = method.CreateDelegate(typeof(Action<Foo,string>)) as Action<Foo,string>;

I think your issue is that you are currently calling the set method is actually the getMethod the error is on this line:: MethodInfo setMethod = typeof(Foo).GetMethod("get_" + propName);

I've never assigned parameter attributes but that may also be an issue too.

Michael B
  • 7,512
  • 3
  • 31
  • 57
2

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.

  • What version of .NET? In .NET4 it gives a security exception to try to call a method that is located on an instance. – Michael B Jan 11 '11 at 16:41
1

What version of .NET does this need to run on? Compiling a delegate from an expression tree would be much easier.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • In .Net 3.5 you can't do assignment in expression trees. –  Jan 04 '11 at 18:52
  • Eh since all he's doing is calling a setter method you could do it in .NET 3.5 as well. Simply go `Expression.Call(target,setMethod,valueExpression)`. It'll appear as `target.set_Property(value)` in the tostring but it works. – Michael B Jan 11 '11 at 16:39