Get pointer value through reflection

I have an instance of a type objectfrom which I know this is a pointer (can be easily checked with myobject.GetType().IsPointer). Is it possible to get the value of a pointer through reflection?

:

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

<h / "> Appendix No. 1: Since the object is a value type - not a reference type, I cannot use GCHandle::FromIntPtr(IntPtr)then GCHandle::Targetto get the value of the object ...

+4
source share
1 answer

I suppose you need a PtrToStructure. Something like that:

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); 
}
+3
source

All Articles