Implementing interfaces is based on the concept of object-oriented programming. With common interfaces, you can use different but similar function blocks the same way.
A function block that implements an interface has to include all methods and properties that are defined in that interface (interface methods and interface properties). This means that the name and the inputs and outputs of the methods or attributes must be exactly the same.
When you create a new function block which implements an interface, CODESYS automatically adds all methods and attributes of the interface to the tree below the new function block.




NOTICE

If you add more interface methods afterwards, then CODESYS does not automatically add these methods to the affected function block. To perform this update, you must execute the “Implement Interfaces” command explicitly.
For inherited function blocks, you have to make sure that any methods or attributes that were derived through the "inheritance" of an interface also receive the appropriate implementation. Otherwise they should be deleted in case the implementation that was provided in the basis should be used. Respective compile error messages or warnings are displayed, prompted automatically by added pragma attributes. For more information, see the help page for the “Implementing Interfaces” command.




NOTICE

-
You must assign the interface of a function block to a variable of the interface type before a method can be called via the variable.
-
A variable of the interface type is always a reference of the assigned function block instance.
A variable of the interface type is a reference to instances of function blocks. This
kind of variable can refer to every function block that implements the interface.
If there is no assignment to a variable, then the variable in online mode contains
the value 0
.
Examples
The I1
interface contains the GetName
method.
METHOD GetName : STRING
The functions blocks A
and B
implements the interface I1
:
FUNCTION_BLOCK A IMPLEMENTS I1 FUNCTION_BLOCK B IMPLEMENTS I1
For this reason, both function blocks must include a method named GetName
and the return type STRING
. Otherwise the compiler reports an error.
A function includes the declaration of a variable of interface I1
type.
FUNCTION DeliverName : STRING VAR_INPUT l_i : I1; END_VAR
Function blocks that implement the I1
interface can be assigned to these input variables.
Examples of function calls:
DeliverName(l_i := A_instance); // call with instance of type A DeliverName(l_i := B_instance); // call with instance of type B
Calling of interface methods:
In this case, it depends on the actual type of l_i
whether the application calls A.GetName
or B.GetName
.
DeliverName := l_i.GetName();