IS4
IS4

Reputation: 13207

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.

Upvotes: 1

Views: 2615

Answers (2)

poizan42
poizan42

Reputation: 1770

An alternative to calling an internal method is to abuse a TypedReference:

    private struct TypedReferenceAccess
    {
        public IntPtr Value;
        public IntPtr Type;
    }

    private static unsafe Type GetTypeFromTypeHandle(IntPtr handle)
    {
        TypedReferenceAccess tr = new TypedReferenceAccess()
        {
            Type = handle
        };
        return __reftype(*(TypedReference*)&tr);
    }

This of course relies on the layout of TypedReference so is really unsafe. But since getting the Type from a TypeHandle is really unsupported you will have to pick your poison if you really want to. Though I would say that I can't help but find it a bit weird that the native TypeHandle is exposed publicly, but without any way of going in the other direction.

Upvotes: 2

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

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

Upvotes: 8

Related Questions