IL使用Reflection.Emit调用带有params object []参数的方法 [英] IL Calling a method with params object[] arguments using Reflection.Emit

查看:76
本文介绍了IL使用Reflection.Emit调用带有params object []参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要以后构建类型的库。图书馆使用平台.Net core 2.0

I'm writing a library that requires a later type build. Library uses platform .Net core 2.0

我正在使用Reflection.Emit生成某种类型的问题

There is issue with some type that I am generating using Reflection.Emit

public class GeneratedA : A, IA
{
    public void DoInterface(string arg0, bool arg1, int arg2, object arg3, List<float> arg4, params object[] otherArgs)
    {
        DoClass(arg0, arg1, arg2, arg3, arg4, otherArgs);
    }
}

以下类型:

public interface IA
{
    void DoInterface(string arg0, bool arg1, int arg2, object arg3, List<float> arg4,  params object[] otherArgs);
}
public class A
{
    public void DoClass(params object[] args)
    {
    }
}

示例IL代码:

class Program
{
    public static class Generator
    {
        public static T Create<T>()
            where T : class
        {
            AssemblyName aName = new AssemblyName("DynamicAssembly");
            AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
            ModuleBuilder mb = ab.DefineDynamicModule(aName.Name);

            var interfaceType = typeof(T);
            var interfaceMethod = interfaceType.GetMethod("DoInterface");
            var interfaceMethodArgs = interfaceMethod.GetParameters().Select(x => x.ParameterType).ToArray();
            var classType = typeof(A);
            var classMethod = classType.GetMethod("DoClass");
            var returnType = typeof(void);
            var baseType = typeof(object);
            var baseConstructor = baseType.GetConstructor(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance, null, Type.EmptyTypes, null);


            TypeBuilder tb = mb.DefineType("GeneratedA", TypeAttributes.Public, baseType);


            ConstructorBuilder ctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
            ILGenerator ctorIL = ctor.GetILGenerator();
            ctorIL.Emit(OpCodes.Ldarg_0);
            ctorIL.Emit(OpCodes.Call, baseConstructor);
            ctorIL.Emit(OpCodes.Nop);
            ctorIL.Emit(OpCodes.Nop);
            ctorIL.Emit(OpCodes.Ret);


            tb.AddInterfaceImplementation(interfaceType);

            MethodBuilder mbIM = tb.DefineMethod(interfaceType.Name + "." + interfaceMethod.Name,
                MethodAttributes.Private | MethodAttributes.HideBySig |
                MethodAttributes.NewSlot | MethodAttributes.Virtual |
                MethodAttributes.Final,
                returnType,
                interfaceMethodArgs);
            ILGenerator genIM = mbIM.GetILGenerator();
            // ToDo
            genIM.Emit(OpCodes.Call, classMethod);
            genIM.Emit(OpCodes.Ret);


            tb.DefineMethodOverride(mbIM, interfaceMethod);

            Type t = tb.CreateType();

            return Activator.CreateInstance(t) as T;
        }

    }

    static void Main(string[] args)
    {
        IA a;
        a = new GeneratedA();
        a.DoInterface("0", true, 2, 3, new List<float>() { 4 }, "5", 6);
        a = Generator.Create<IA>();
        a.DoInterface("0", true, 2, 3, new List<float>() { 4 }, "5", 6);
    }
}

无论何时我尝试填写评论 ToDo ,出现错误公共语言运行库检测到无效程序。

Whenever I try to fill out a comment "ToDo", I get an error "Common Language Runtime detected an invalid program".

我要求帮助调用方法DoClass。

I ask to help with a call of method DoClass.

谢谢

推荐答案

要调用 DoClass 方法,需要提供参数,只是调用classMethod 不起作用。

To call DoClass method you need to provide arguments, just Call classMethod isn't going to work.

第一个参数当然是 引用:

First argument is of course "this" reference:

genIM.Emit(OpCodes.Ldarg_0);

第二个参数是对象数组。 params 是编译器功能,如果您自己构建代码,则必须将其视为 params 不存在。我的意思是-而

Second argument is array of objects. params is compiler feature, if you build code yourself - you have to treat it as if params is not there. What I mean is - while

 DoClass();

在用代码编写时是合法的-编译为:

is legal when you write it in code - this is compiled as:

DoClass(new object[0]);

因此,在发出此调用时-应该始终提供对象数组参数,不能忽略它

So when you are emitting this call - you should always provide array of objects argument, you cannot omit it.

将对象数组推入堆栈:

// push array length (0, for example) to stack
genIM.Emit(OpCodes.Ldc_I4_0); 
// push new array with length given by the above value (0)
genIM.Emit(OpCodes.Newarr, typeof(object)); 

此时,您的代码将编译并运行良好。这类似于:

At this point your code will compile and run fine. This is analog of:

public class GeneratedA : A, IA
{
    public void DoInterface(string arg0, bool arg1, int arg2, object arg3, List<float> arg4, params object[] otherArgs)
    {
        DoClass();
    }
}

如果要传递<$ c的所有参数$ c> DoInterface ,这需要做更多的工作。我将提供一些示例。传递第一个参数(字符串arg0 ):

If you want to pass all arguments of DoInterface, that requires more work. I'll provide couple examples. To pass first argument (string arg0):

genIM.Emit(OpCodes.Dup);
// push index to store next element at (0)
genIM.Emit(OpCodes.Ldc_I4_0);
// push first argument (arg0 of DoInterface) to stack
genIM.Emit(OpCodes.Ldarg_1);
// store element in array at given index (yourArguments[0] = arg0)
genIM.Emit(OpCodes.Stelem_Ref);

传递第二个参数:

genIM.Emit(OpCodes.Dup);
// push index to store next element at (1)
genIM.Emit(OpCodes.Ldc_I4_1);
// push arg2
genIM.Emit(OpCodes.Ldarg_2);
// box, because boolean is value type, and you store it in object array
genIM.Emit(OpCodes.Box, typeof(bool));
// store in array (yourArguments[1] = (object) arg2
genIM.Emit(OpCodes.Stelem_Ref);

以此类推。

当您将参数推入数组时,不要忘记更改其长度以反映数字参数:

When you will push arguments into your array, don't forget to change its length to reflect number of arguments:

// push array length - 6
genIM.Emit(OpCodes.Ldc_I4_6); 
// push new array with length given by the above value (6)
genIM.Emit(OpCodes.Newarr, typeof(object)); 

另请注意,您可能需要更改:

Note also that you might want to change:

TypeBuilder tb = mb.DefineType("GeneratedA", TypeAttributes.Public, baseType);

to

TypeBuilder tb = mb.DefineType("GeneratedA", TypeAttributes.Public, classType);

或者只是更改为 baseType = typeof(A),因为您想从<$继承生成的类c $ c> A ,而不是来自 object

Or just change to baseType = typeof(A), because you want to inherit your generated class from A, not from object.

使用前两个参数发出呼叫的完整代码:

Full code to emit call with first 2 args:

ILGenerator genIM = mbIM.GetILGenerator();            
genIM.Emit(OpCodes.Ldarg_0);   
genIM.Emit(OpCodes.Ldc_I4_2);
genIM.Emit(OpCodes.Newarr, typeof(object));

genIM.Emit(OpCodes.Dup);
genIM.Emit(OpCodes.Ldc_I4_0);
genIM.Emit(OpCodes.Ldarg_1);
genIM.Emit(OpCodes.Stelem_Ref);

genIM.Emit(OpCodes.Dup);
genIM.Emit(OpCodes.Ldc_I4_1);
genIM.Emit(OpCodes.Ldarg_2);
genIM.Emit(OpCodes.Box, typeof(bool));
genIM.Emit(OpCodes.Stelem_Ref);

genIM.Emit(OpCodes.Call, classMethod);
genIM.Emit(OpCodes.Ret);

这篇关于IL使用Reflection.Emit调用带有params object []参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆