TwinCAT Engineering Notes
← All posts

A Non-Obvious Pitfall with Resource Cleanup in TwinCAT Programs

Why FB_init and FB_exit inside TwinCAT programs (static classes) are not called automatically, and how to bypass this limitation.

By resource cleanup, I mean things like freeing dynamically allocated memory, closing a file handler, closing a connection, and similar operations.

This issue primarily affects TwinCAT versions 3.1.4024 and earlier, because these versions allowed developers to create FB_init and FB_exit methods directly inside programs. The trap is that these methods are not called automatically.

If you need to release resources when a program is deleted, here is an approach I can propose:

  1. Create an internal method inside the program dedicated to resource cleanup, for example ReleaseResources().
  2. Create a dedicated class responsible solely for resource cleanup, for example MainProgramResourceManager.
  3. Implement FB_exit inside this class, and call the program’s cleanup method from it, for example MAIN.ReleaseResources().
  4. Instantiate this class inside the program, for example:
    _resourcemanager : MainProgramResourceManager;

That’s it. When the program is deleted, all its internal variables—including the resource manager—are deleted automatically. And since the resource manager is an object, its FB_exit method will be called automatically as well. This allows you to bypass this compiler limitation.

The same principle can be applied to initialization logic too.

Resource Cleanup Pitfall Demonstration

#TwinCAT #CoDeSys #OOP #StructuredText #IndustrialAutomation