samedi 28 mai 2016

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





Aucun commentaire:

Enregistrer un commentaire