Skip to content

Instantly share code, notes, and snippets.

@Kir-Antipov
Last active January 12, 2021 07:22
Show Gist options
  • Save Kir-Antipov/fcb09ed4065e9cece8a62bcdb9f37bb2 to your computer and use it in GitHub Desktop.
Save Kir-Antipov/fcb09ed4065e9cece8a62bcdb9f37bb2 to your computer and use it in GitHub Desktop.
Get the interfaces implemented by the object
// A little bit faster then standard Type.GetInterfaces()
public static Type[] GetInterfaces(object Obj)
{
unsafe
{
TypedReference trObj = __makeref(Obj);
IntPtr ptrObj = **(IntPtr**)&trObj;
void* methodTable = (*(IntPtr*)ptrObj.ToPointer()).ToPointer();
int count = ((ushort*)methodTable)[7];
IntPtr* interfaces = (IntPtr*)((IntPtr*)methodTable)[9].ToPointer();
Type[] result = new Type[count];
for (int i = 0; i < count; ++interfaces, ++i)
result[i] = GetTypeFromHandleUnsafe(*interfaces);
return result;
}
}
private static readonly Func<IntPtr, Type> GetTypeFromHandleUnsafe = (Func<IntPtr, Type>)typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic).CreateDelegate(typeof(Func<IntPtr, Type>), null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment