Skip to content

Instantly share code, notes, and snippets.

@Kir-Antipov
Created February 19, 2019 08:24
Show Gist options
  • Save Kir-Antipov/cd3f9954a2d35cbdc0082d427b6c1e62 to your computer and use it in GitHub Desktop.
Save Kir-Antipov/cd3f9954a2d35cbdc0082d427b6c1e62 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(Type ObjectType, Type InterfaceType)
{
unsafe
{
IntPtr iMTPointer = InterfaceType.TypeHandle.Value;
void* methodTable = ObjectType.TypeHandle.Value.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