带有ref / Pointer参数的C#反射调用方法

时间:2015-06-18 09:21:38

标签: c# pointers reflection ref

我想用反射调用类的每个方法,但是我不能用指针调用方法作为参考。通常我只能为我找到的每个指针传递null,一切都会好的。问题是当函数试图访问我传递的指针时。指针将是对内存地址0的引用,这显然是我程序的即时崩溃。 所以我需要将指针传递给有效的内存地址,但我不知道如何在运行时创建指针

我的代码的压缩版本:

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 *,正是我必须传递给函数...

1 个答案:

答案 0 :(得分:8)

首先,让我们将其分为指针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;
    }
}