[英]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)
}
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.