Dje*_*sen 1 c# reflection pointers 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() });
}
}
Run Code Online (Sandbox Code Playgroud)
和TestClass:
public class TestClass
{
unsafe public void Test(char* pointer)
{
}
public void Test2(ref int reference)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我总是得到异常"System.RuntimeType"无法转换为类型'System.Char*'奇怪的是,pointerInstance.GetType().MakePointerType()返回一个char*,正好是我必须传入的功能...
首先,让我们把它分成指针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';
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Received: x
After call, c = y
Run Code Online (Sandbox Code Playgroud)
对于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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2414 次 |
| 最近记录: |