首先,让我们将其分为指针与ref
- 它们的处理方式略有不同。
不清楚你的指针值是什么expected接收方法 - 特别是您传递给的值Invoke
是一种类型,而不是该类型的实例 - 但您应该使用Pointer.Box https://msdn.microsoft.com/en-us/library/system.reflection.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';
}
}
Output:
Received: x
After call, c = y
For 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;
}
}