Home All Groups Group Topic Archive Search About

Bug: DynamicMethod field access to generic type members

Author
12 Mar 2007 2:36 PM
hessi9
I use DynamicMethods for data serialisation and it works well until I
tried get access to members fields from generic type instanzes. There
I always get a FieldAccessException even if the accessed field is
public. I'm shure it is a bug, as the same IL-code works well when it
is generated into a assembly or the referenced field is not part of a
generic. A litte bit more surprising for me was to see that the same
code works when the DynamicMethod was bound to a system type like
object. But this doesn't help me as I like to access internal or
protected fields and not public once.

As I haven't found information at the web that someone else already
had the same problems I post it here in the hope that it will get
fixed earlier or later... A fix would be nice as traditional
reflection is so solw :-(

Here is a realy short example program to demonstrate the bug:

using System;
using System.Reflection;
using System.Reflection.Emit;

public class MyGeneric<T> {
  public int number = 25;
}
public delegate int GetDelegate(MyGeneric<object> a);

class Program {
  static void Main(string[] args) {
    DynamicMethod method2 = new DynamicMethod("MyGetVal", typeof(int),
new Type[] { typeof(MyGeneric<object>) }, typeof(Program));
    FieldInfo fieldInfo =
typeof(MyGeneric<object>).GetField("number");
    ILGenerator ilGen = method2.GetILGenerator();
    ilGen.Emit(OpCodes.Ldarg_0);
    ilGen.Emit(OpCodes.Ldfld, fieldInfo);
    ilGen.Emit(OpCodes.Ret);
    GetDelegate del =
(GetDelegate)method2.CreateDelegate(typeof(GetDelegate));
    Console.WriteLine(del(new MyGeneric<object>()));
  }
}

AddThis Social Bookmark Button