Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


Addendum №1: As the object in question is value type -not a reference type-, I cannot use GCHandle::FromIntPtr(IntPtr) followed by GCHandle::Target to obtain the object's value...
like image 391
unknown6656 Avatar asked May 28 '16 14:05

unknown6656


1 Answers

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); 
}
like image 143
Evk Avatar answered Oct 27 '22 11:10

Evk