与REF /指针参数C#反射调用方法(C# Reflection Call Method with

2019-10-23 10:46发布

我想和反射来调用类的每一个方法,但我不能调用方法与指针作为参考。 通常我只可以传递null每个指针我发现,一切都将被罚款。 问题是,当函数改掉访问我通过指针。 指针是将内存地址为0的参考,这是很明显对我的计划瞬间崩溃。 所以,我需要一个指针传递给有效的内存ADRESS,但我不知道我怎么可以在运行时创建一个指针

我的代码的压缩版本:

class Program
{
    static void Main(string[] args)
    {
        var obj = new TestClass();
        var pointerMethod = obj.GetType().GetMethod("Test");
        var referenceMethod = obj.GetType().GetMethod("Test2");

        var pointerParameter = pointerMethod.GetParameters()[0];
        var referenceParameter = referenceMethod.GetParameters()[0];

        //Get the instance of the class that is referred by the pointer/reference
        var pointerInstance = Activator.CreateInstance(pointerParameter.ParameterType.GetElementType());
        var referenceInstance = Activator.CreateInstance(referenceParameter.ParameterType.GetElementType());

        //Call the method and "cast" the char instance into an pointer
        pointerMethod.Invoke(obj, new[] {pointerInstance.GetType().MakePointerType()});
        referenceMethod.Invoke(obj, new[] { referenceInstance.GetType().MakeByRefType() });
     }
}

和识别TestClass:

public class TestClass
{
        unsafe public void Test(char* pointer)
        {

        }

        public void Test2(ref int reference)
        {

        }
}

我一直得到的异常“System.RuntimeType”不能转换为类型“System.Char *”奇怪的是,pointerInstance.GetType()。MakePointerType()返回一个char *,正是我要传递到功能...

Answer 1:

首先,让我们这个分成指针VS ref -他们稍有不同的处理。

目前还不清楚是什么指针值你所期望的方法来领取-尤其当你传递给值Invoke是一个类型,而不是类型的实例-但你应该使用Pointer.Box

using System.Reflection;

class TestPointer
{    
    unsafe static void Main()
    {
        char c = 'x';
        char* p = &c;
        object boxedPointer = Pointer.Box(p, typeof(char*));

        var method = typeof(TestPointer).GetMethod("Foo");
        method.Invoke(null, new[] { boxedPointer });
        Console.WriteLine("After call, c = {0}", c);
    }

    public static unsafe void Foo(char *pointer)
    {
        Console.WriteLine("Received: {0}", *pointer);
        *pointer = 'y';
    }
}

输出:

Received: x
After call, c = y

对于ref参数,它是稍微简单-你只允许正常的拳击,和参数数组改变了:

using System.Reflection;

class TestRef
{    
    unsafe static void Main()
    {
        var method = typeof(TestRef).GetMethod("Foo");
        var args = new object[] { 10 };
        method.Invoke(null, args);
        Console.WriteLine("After call, args[0] = {0}", args[0]);
    }

    public static unsafe void Foo(ref int x)
    {
        Console.WriteLine("Received: {0}", x);
        x = 20;
    }
}


文章来源: C# Reflection Call Method with ref/Pointer Parameter