通过反射

时间:2016-05-28 14:51:50

标签: c# pointers reflection

我有一个object类型的实例,我知道它是一个指针(可以很容易地用myobject.GetType().IsPointer进行验证)。是否可以通过反射获得指针的值?

到目前为止

代码:

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)
}

<小时/> 附录№1:由于相关对象是值类型 - 不是引用类型 - ,我无法使用GCHandle::FromIntPtr(IntPtr)后跟GCHandle::Target来获取对象的价值......

1 个答案:

答案 0 :(得分:4)

我想你需要的是PtrToStructure。像这样:

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); 
}