[英]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)
}
GCHandle::FromIntPtr(IntPtr)
followed by GCHandle::Target
to obtain the object's value...
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.