Search code examples
c#.netclr

Type from IntPtr handle


Is it possible to obtain the System.Type object from an IntPtr type handle (that can be obtained by Type.TypeHandle.Value)?

Example:

TypeFromIntPtr(typeof(object).TypeHandle.Value) == typeof(object) //true

Edit: I am glad there are many helpful people that think I am trying to solve something else, but I am seeking the answer to this particular problem and I am really sure about it. I am sorry for not specifying it in the first place.

Edit #2: Type handle is a pointer that points to the structure that represents RTTI in the CLR. I don't want to read data from this structure, I want a way that returns the managed Type object for this. I need to "convert" the pointer to the object.


Solution

  • We usually won't allow anyone to shoot their foot, but you seem to be insisting that you need to, and you know what you're doing.

    Here's how you shoot your foot:

    private static Type GetTypeFromHandle(IntPtr handle)
    {
        var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic);
        return (Type)method.Invoke(null, new object[] { handle });
    }
    
    private static void Main(string[] args)
    {
        IntPtr handle = typeof(string).TypeHandle.Value;//Obtain handle somehow
    
        Type type = GetTypeFromHandle(handle);
    }