发出呼吁System.Lazy< T>构造函数Mono.Cecil能做到能做到、函数、LT、System

2023-09-03 02:04:33 作者:指尖滑落的雨滴

我想发出实例化一个System.Lazy和方法的无效令牌一PEVerify错误失败,在该行 newobj实例无效类[mscorlib程序] System.Lazy`1&LT ;类Example.ExpensiveType> ::构造函数(类[mscorlib程序] System.Func`1<类Example.ExpensiveType>)。

I'm trying to emit a method that instantiates a System.Lazy and failing with a PEVerify error of "Invalid token", at the line newobj instance void class [mscorlib]System.Lazy`1<class Example.ExpensiveType>::.ctor(class [mscorlib]System.Func`1<class Example.ExpensiveType>)

展望与其他地方ILDASM,我看到一个适当的调用是这样的:

Looking elsewhere with ILDasm, I see that a proper call would look like this:

newobj     instance void class [mscorlib]System.Lazy`1<class Example.IHeater>::.ctor(class [mscorlib]System.Func`1<!0>)

不幸的是,我在一个不知如何与Mono.Cecil能做到API重现此。谁能帮与泛型?

Unfortunately, I'm at a loss as to how to reproduce this with the Mono.Cecil API. Can someone help with the generics?

这是我迄今:

var get = new MethodDefinition(
            "Get",
            MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual,
            ModuleDefinition.TypeSystem.Object);

var funcType = new GenericInstanceType(ImportedTypes.FuncOfT);
funcType.GenericArguments.Add(lazyElementType);

var funcTypeCtor = new MethodReference(".ctor", ModuleDefinition.TypeSystem.Void, funcType);
funcTypeCtor.Parameters.Add(new ParameterDefinition(ModuleDefinition.TypeSystem.Object));
funcTypeCtor.Parameters.Add(new ParameterDefinition(ModuleDefinition.TypeSystem.IntPtr));
funcTypeCtor.HasThis = true;
funcTypeCtor = ModuleDefinition.Import(funcTypeCtor);

var lazyTypeCtor = new MethodReference(".ctor", ModuleDefinition.TypeSystem.Void, lazyType);
var parameterDefinition = new ParameterDefinition(funcType);
lazyTypeCtor.Parameters.Add(parameterDefinition);
lazyTypeCtor.HasThis = true;
lazyTypeCtor = ModuleDefinition.Import(lazyTypeCtor);

il = get.Body.GetILProcessor();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldftn, getTypedValue);
il.Emit(OpCodes.Newobj, funcTypeCtor);
il.Emit(OpCodes.Newobj, lazyTypeCtor);  // This leads to the invalid token
il.Emit(OpCodes.Ret);
lazyBinding.Methods.Add(get);

任何帮助将是非常美联社preciated - !我难倒

Any help would be much appreciated - I'm stumped!

推荐答案

我发现埋在一岁的邮件列表归档的答案(感谢的GaborKozár!)。我没有正确创建/导入泛型类型和他们的方法。在code是正确加载延迟&LT; T&GT; Func键&LT; T&GT; 类型如下:

I've discovered the answer buried in a years-old mailing list archive (thanks to Gábor Kozár!). I was not properly creating/importing generic types and their methods. The code that properly loads the Lazy<T> and Func<T> types follows:

var genericArgument = lazyElementType;
var funcType = ModuleDefinition.Import(typeof(Func<>)).MakeGenericInstanceType(genericArgument);
var funcCtor =
    ModuleDefinition.Import(funcType.Resolve()
                                    .Methods.First(m => m.IsConstructor && m.Parameters.Count == 2))
                    .MakeHostInstanceGeneric(genericArgument);

var lazyType = ModuleDefinition.Import(typeof(Lazy<>)).MakeGenericInstanceType(genericArgument);
var lazyCtor =
    ModuleDefinition.Import(lazyType.Resolve()
                                    .GetConstructors()
                                    .First(m => m.Parameters.Count == 1
                                             && m.Parameters[0].ParameterType.Name.StartsWith("Func")))
                    .MakeHostInstanceGeneric(genericArgument);

// Method body as above

键上面是扩展方法 MakeHostInstanceGeneric ,其定义为

public static MethodReference MakeHostInstanceGeneric(
                                  this MethodReference self,
                                  params TypeReference[] args)
{
    var reference = new MethodReference(
        self.Name,
        self.ReturnType,
        self.DeclaringType.MakeGenericInstanceType(args))
    {
        HasThis = self.HasThis,
        ExplicitThis = self.ExplicitThis,
        CallingConvention = self.CallingConvention
    };

    foreach (var parameter in self.Parameters) {
        reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
    }

    foreach (var genericParam in self.GenericParameters) {
        reference.GenericParameters.Add(new GenericParameter(genericParam.Name, reference));
    }

    return reference;
}