Skip to content

Instantly share code, notes, and snippets.

@Kir-Antipov
Created February 19, 2019 08:19
Show Gist options
  • Save Kir-Antipov/a8986bf93a61b1d74da4ef654c9459b9 to your computer and use it in GitHub Desktop.
Save Kir-Antipov/a8986bf93a61b1d74da4ef654c9459b9 to your computer and use it in GitHub Desktop.
Quick check whether the object implements the interface
// It's twice slower then `Obj is IMyInterface`
// But it's twice faster then any other check
// Based on my SO answer: https://ru.stackoverflow.com/a/945958/248572
public static bool Implements(object Obj, Type InterfaceType)
{
unsafe
{
// MT Pointer of our interface
IntPtr iMTPointer = InterfaceType.TypeHandle.Value;
// Object's ref
TypedReference trObj = __makeref(Obj);
IntPtr ptrObj = **(IntPtr**)&trObj;
void* methodTable = (*(IntPtr*)ptrObj.ToPointer()).ToPointer();
IntPtr* interfaces = (IntPtr*)((IntPtr*)methodTable)[9].ToPointer();
int count = ((ushort*)methodTable)[7];
for (int i = 0; i < count; ++interfaces, ++i)
if (*interfaces == iMTPointer)
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment