Created
February 19, 2019 08:24
-
-
Save Kir-Antipov/cd3f9954a2d35cbdc0082d427b6c1e62 to your computer and use it in GitHub Desktop.
Quick check whether the object implements the interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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