【问题标题】:Reflection.emit System.InvalidProgramException: Common Language Runtime detected an invalid programReflection.emit System.InvalidProgramException:公共语言运行时检测到无效程序
【发布时间】:2013-06-05 21:32:48
【问题描述】:

我是反射.emit 的新手,一直在尝试生成以下 c# 代码:

public class RepositoryWrapper
{
    public void CallRepositoryMethod(IAddressRepository repository, Address address)
    {
        repository.NODE_I_NodeExtendedDetails_Address3(address.NodeId);
    }
}

这是它的 il 表示:

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: ldarg.2
    IL_0003: callvirt instance int32 ReflectionServices.Node::get_NodeId()
    IL_0008: callvirt instance void ReflectionServices.IAddressRepository::NODE_I_NodeExtendedDetails_Address3(int32)
    IL_000d: nop
    IL_000e: ret

这是我用来创建它的代码:

 internal static void Generate(this System.Reflection.Emit.ILGenerator @this, Type target,string method,Type instance)
        {

        var methodToCall = target.GetMethod(method);
        var methodParams = methodToCall.GetParameters();
        var instanceProperties = instance.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        var orderedProperties = (from mp in methodParams
                              join p in instanceProperties
                              on mp.Name.ToLower() equals p.Name.ToLower()
                              select p).ToArray();

        //add properties to the string builder

        //load the object reference onto the stack sothat we can access its methods
        @this.Emit(OpCodes.Nop);
        @this.Emit(OpCodes.Ldarg_1);
        @this.Emit(OpCodes.Ldarg_2);

            var property = orderedProperties.FirstOrDefault(x => x.Name == "NodeId");
            if (property != null)
            {
                var getMethod = property.GetGetMethod();
                @this.Emit(getMethod.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, getMethod);

            }


        //call method 
            @this.Emit(methodToCall.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, methodToCall);
            @this.Emit(OpCodes.Nop);
        //return from function
        @this.Emit(OpCodes.Ret);
        }

这是我得到的错误:

System.InvalidProgramException: Common Language Runtime detected an invalid program.
Result StackTrace:  
at ReflectionServices.Repository.NODE_I_NodeExtendedDetails3_Address40807399(Repository      target, Address )

这是生成的 il:

nop
ldarg.1
ldarg.2
call instance int32 ReflectionServices.Node::get_NodeId()
callvirt instance void            
ReflectionServices.Repository::
                               NODE_I_NodeExtendedDetails3_Address(int32)
nop

任何人都可以看到我遇到了什么问题吗?

谢谢

这是我要求的 dll 和方法:

 public sealed class ReflectionEmitWithDebuggingMethodGenerator
{
    private AssemblyBuilder Assembly { get; set; }
    private ModuleBuilder Module { get; set; }
    private AssemblyName Name { get; set; }

    public ReflectionEmitWithDebuggingMethodGenerator()
        : base()
    {
        this.Name = new AssemblyName() { Name = Guid.NewGuid().ToString("N") };
        this.Assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
            this.Name, AssemblyBuilderAccess.RunAndSave,@"C:\Users\darren\Documents\Visual Studio 2012\Projects\UnityInjection");
        this.AddDebuggingAttribute(this.Assembly);
        this.Module = this.Assembly.DefineDynamicModule(this.Name.Name + ".dll", true);
    }
   public Action<TObject, TInstance> Generate<TObject, TInstance>(Type target, string methodN, Type instanceType)
    {
        var type = this.Module.DefineType(target.Namespace + "." + target.Name);
        var methodName = methodN + target.GetHashCode().ToString();
        var method = type.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { target, instanceType });
        method.DefineParameter(1, ParameterAttributes.In, "target");
        method.DefineParameter(2, ParameterAttributes.In, "instance");

        ILGenerator.Generate(method.GetILGenerator(), target,methodN,instanceType);

        var createdType = type.CreateType();

        var createdMethod = createdType.GetMethod(methodName);
        return (Action<TObject, TInstance>)Delegate.CreateDelegate(typeof(Action<TObject, TInstance>), createdMethod);
    }


}

【问题讨论】:

  • 调用生成的程序集时出现错误,对吧?您是否将生成的 IL 与您正在建模的 IL 进行了比较?
  • 是的,我在执行函数时遇到错误。我已经用生成的 Il 更新了帖子
  • 如何检查生成的 IL?您是否将程序集转储到磁盘,然后用 Reflector 之类的东西打开它?
  • 不,我把它写到一个文件中,这样我就可以用它来调试了
  • PEVerify 对生成的程序集有何看法?

标签: c# reflection.emit


【解决方案1】:

比较编译和发出的输出,只有一个区别:

编译:

callvirt instance int32 ReflectionServices.Node::get_NodeId()

发射:

call instance int32 ReflectionServices.Node::get_NodeId()

您调用int32 get_NodeId() 的类型是ReflectionServices.Node,但您传递给您尝试复制的方法的对象类型是Address。这让我相信ReflectionServices.Node 上定义的属性访问器必须被虚拟调用,可能是因为它继承自另一个在ReflectionServices.Node 实现该属性之前声明该属性的类(或实现了一个接口)。

当您发出该行代码时,只需虚拟调用它:

@this.Emit(OpCodes.Callvirt, getMethod);

编辑:根据进一步提供的代码,这是真正的解决方案。

因此,您在实现接口的基础上存在问题:

var method = type.DefineMethod(methodName, MethodAttributes.Static | Method...
//                                                          ^^^^^^

接口方法不是静态的;他们是实例成员。因此,您首先需要在创建MethodBuilder 时从属性标志中删除MethodAttributes.Static

其次,当你返回这个函数时,你必须包含一个目标对象,它是调用方法的实例。为此,您可以使用Activator.CreateInstance 调用默认生成的构造函数,并为您提供一个实例化对象以用作目标。用这些行替换 Generate 方法的最后一行来实现这一点。

var activatedObject = Activator.CreateInstance(type);

return (Action<TObject, TInstance>)Delegate.CreateDelegate(
    typeof(Action<TObject, TInstance>), activatedObject, createdMethod);

【讨论】:

  • 你是对的,Address 类继承自具有 NodeId 属性的 Node。我尝试了您的更改并刚刚调用了 OpCodes.Callvirt 但它仍然有相同的错误...
  • 好吧,如果生成的 IL 匹配,那么一定是其他问题。你能修改你的帖子,包括你对DefineTypeDefineMethod的电话吗?
  • 我已经在上面添加了我的定义方法和类型。
  • 我发现了你的问题。试一试。
  • 第二个参数呢?
猜你喜欢
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 2016-08-13
  • 2018-02-17
  • 1970-01-01
  • 2017-05-05
  • 2011-05-05
  • 1970-01-01
相关资源
最近更新 更多