TwinCAT Engineering Notes
← All posts

Dynamic Object Creation in TwinCAT using FB_Init Parameters

How to dynamically create a class instance in TwinCAT when the class has additional parameters in FB_Init.

How to dynamically create a class instance in TwinCAT when the class has additional parameters in FB_Init?

If you have a class that requires parameters in its constructor, dynamically creating an instance is usually straightforward — unless you’re working with Structured Text (ST).

ST brings two surprises here:

  1. Classes (still referred to as function blocks) do not have constructors, but they can include a single FB_Init method with optional parameters.
  2. The documentation explains how to create an instance without parameters, but does not describe how to instantiate a class whose FB_Init requires parameters.

I eventually discovered how to do this: after the class type, inside parentheses, you must list all parameters explicitly, using their names and values.

Here is the syntax:

VAR
    <object> : POINTER TO <Class>;
END_VAR

<object> := __NEW(
    <Class>(
        <parameter_1_Name> := <value_For_Parameter_1>
        [, <parameter_N_Name> := <value_For_Parameter_N>]
    )
);

A real example is shown in the screenshot below.

__NEW code screenshot

#TwinCAT, #CoDeSys, #OOP, #StructuredText, #FB_Init, #__NEW