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
). 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...
I suppose what you need is 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With