Type Checking at Runtime in TwinCAT: __QUERYINTERFACE and __QUERYPOINTER
An exploration of runtime type safety in Structured Text, detailing how to check type compatibility using interfaces and compiler casting operators.
In StructuredText, there is no built-in operator for type compatibility checking. However, CoDeSys/TwinCAT gives us some additional options: you can attempt to cast a variable containing an object into a variable of an interface type using the __QUERYINTERFACE operator.
The runtime will perform a type compatibility check during program execution, and the operator will return TRUE only if the object implements the corresponding interface. This works with interfaces that inherit from __SYSTEM.IQueryInterface. Of course, this does not replace the missing IS operator, but it is better than nothing.
Interestingly, this functionality does not work with __QUERYPOINTER. This is mentioned in the documentation, but it does not look very natural.
So interfaces are the only way to delegate type compatibility checking to the runtimeā¦

#TwinCAT #CoDeSys #StructuredText #IndustrialAutomation