StructuredText Cheat Sheet: Types, FB, Classes, and Objects
An explanation of core object-oriented concepts in the TwinCAT/CoDeSys implementation of Structured Text.
Type, Function Block (FB), Program, Class, Static Class, Class Instance, Object – what is what?
I apologize to anyone who may find this post simplistic. I hesitated for a long time about whether to publish it, but I often encounter situations where people do not understand the very basics. So let it be — I hope someone will find it useful.
This is a cheat sheet for the StructuredText language in its TwinCAT/CoDeSys implementation, as I understand it.
📌 A ‘Function Block’ (FB) in the current implementation is equivalent to a ‘Class’. Only two differences come to mind:
- An FB can have something like a method without a name, which a classic class does not allow: compare
Timer()andTimer.Execute(). The first is not allowed for a classic class and can be prohibited for an FB using the{attribute 'no_explicit_call'}attribute. - There are concepts of ‘Action’ and ‘Transition’, but you can consider them simply as specific methods to use with SFC (Sequential Function Chart).
📌 A ‘Static Class’ and a ‘Program’ (PRG) are the same thing, with the same features as for a function block/class.
📌 A ‘Class Instance’ and an ‘Object’ are the same thing, said in two different words. You can think that a class is a blueprint from which an object can be created at runtime.
📌 A ‘Static Class’ is like a regular class with a few nuances:
- The variable and the class instance are created by the compiler automatically.
- There is always exactly one instance, no more, no less.
- The variable representing the instance and the type have the same name.
FB_initandFB_exitare not executed for static classes by the compiler.
📌 A ‘Type’ is a set of rules used by the compiler (how to allocate memory, how the data is represented, which operations are allowed, etc.).
📌 A ‘Class’ is a way for the programmer to explain to the compiler how to create a new type: for each class, the compiler creates a new type with the same name.
💡 Important points:
- All classes define types, but not all types are classes (numbers, strings, structures, interfaces, etc. are not classes).
- The compiler works at the level of types.
- For types created for classes and structs, the compiler allows assigning a descendant object to a variable of an ancestor type, but not vice versa.
- The compiler restricts access to an object based on the type of the variable, not the type of the actual object that exists in memory.
You can find more samples here: https://github.com/trofimich/TwinCAT.OpenFramework

#TwinCAT #CoDeSys #PLC #IEC61131 #StructuredText #IndustrialAutomation