TwinCAT Engineering Notes
← All posts

Nuances of Working with Function Block Instances by Value in TwinCAT 3 / CoDeSys

A detailed analysis of memory copying (MEMCPY) and object lifecycle (FB_Init/FB_Exit) when working with function block instances by value in IEC 61131-3.

Imagine you have a class (function block) and you are working with its instances by value. Here is a checklist of questions to keep in mind:

• What happens when you assign the value of one class variable to another? • What happens when you assign the result of a method or function to such a variable? • What happens if you try to assign an object returned by a method or function to an interface variable?

Here is what actually happens “under the hood” in three typical scenarios:

1️⃣ Direct Assignment (fb_B := fb_A;)

What happens: A hidden MEMCPY occurs—a bitwise copy of raw data from one memory location to another.

Lifecycle: Since both objects already exist in memory, the FB_Init and FB_Exit methods are NOT called; only the data is overwritten.

Important: If the FB contains pointers (POINTER TO), references (REFERENCE TO), or interfaces, only their addresses will be copied. Modifying data in one block will unexpectedly alter it in the other. This also applies to memory deallocation.

2️⃣ Returning an FB via a METHOD by Value (METHOD GetBlock : MyFB)

What happens: The compiler allocates a temporary buffer on the stack to store the return value.

Lifecycle: When the method is called, FB_Init automatically triggers for this buffer, and upon method completion, FB_Exit is called.

Important: If you call this method on every PLC cycle, FB_Init / FB_Exit will be executed continuously.

3️⃣ Assigning the Result of Such a Method to an INTERFACE

What happens: Fortunately, the compiler strictly prohibits this implicitly.


💡 Conclusions:

Working with objects by value in a PLC environment has its specific constraints. In most cases, it is much more efficient to pass references, pointers, or interfaces to objects that permanently reside in the static PLC memory.

If you come from a C++ background, it is best to think of function blocks as data structures with attached methods. There are no classical constructors, copy constructors, destructors, or operator overloads. There are only FB_Init and FB_Exit—which mirror constructors and destructors but operate under their own unique rules.

#TwinCAT3 #PLC #Beckhoff #IEC61131_3 #StructuredText #Automation #Embedded