简体   繁体   English

通过反射获取指针值

[英]Get pointer value via reflection

I have an instance of the type object , from which I know that it is a pointer (can easily be verified with myobject.GetType().IsPointer ). 我有一个类型object的实例,我知道它是一个指针(可以很容易地用myobject.GetType().IsPointer验证myobject.GetType().IsPointer )。 Is it possible to obtain the pointer's value via reflection? 是否可以通过反射获得指针的值?

code so far: 代码到目前为止:

object obj = .... ; // type and value unknown at compile time
Type t = obj.GetType();

if (t.IsPointer)
{
    void* ptr = Pointer.Unbox(obj);

    // I can obtain its (the object's) bytes with:
    byte[] buffer = new byte[Marshal.SizeOf(t)];
    Marshal.Copy((IntPtr)ptr, buffer, 0, buffer.Length);

    // but how can I get the value represented by the byte array 'buffer'?
    // or how can I get the value of *ptr?
    // the following line obviously doesn't work:
    object val = (object)*ptr; // error CS0242 (obviously)
}


Addendum №1: As the object in question is value type -not a reference type- , I cannot use GCHandle::FromIntPtr(IntPtr) followed by GCHandle::Target to obtain the object's value... 附录№1:由于有问题的对象是值类型- 不是引用类型-我不能使用GCHandle::FromIntPtr(IntPtr)后跟GCHandle::Target来获取对象的值...

I suppose what you need is PtrToStructure. 我想你需要的是PtrToStructure。 Something like this: 像这样的东西:

if (t.IsPointer) {
    var ptr = Pointer.Unbox(obj);

    // The following line was edited by the OP ;)
    var underlyingType = t.GetElementType();
    var value = Marshal.PtrToStructure((IntPtr)ptr, underlyingType); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM