簡體   English   中英

通過反射獲取指針值

[英]Get pointer value via reflection

我有一個類型object的實例,我知道它是一個指針(可以很容易地用myobject.GetType().IsPointer驗證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來獲取對象的值...

我想你需要的是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); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM