Operator ‘__NEW’

This operator is an extension of the IEC 61131-3 standard.

The __NEW operator reserves memory for function block instances or arrays of standard data types. The operator returns a matching typed pointer to the object. If you do not use the operator within an assignment, then CODESYS prints an error message.

If the attempt to allocate memory fails, then __NEW returns the value 0.

Requirement: In the properties dialog of the application, the Use dynamic memory allocation check box is selected in the Application build options tab.

__NEW(yType>,[<size>])

The operator generates an instance of the specified type <type> and returns a pointer to this instance. Then CODESYS calls the initialization of the instance.

If the <type> is a scalar, then CODESYS also sets the optional operand <size>. Then the operator generates a array of type <type> and size <size>.

Example

pScalarType := __New(ScalarType, length);

Attention

A function block that can be created with __NEW has a fixed memory area. It cannot modify its data layout by means of an online change. Therefore, new variables cannot be added or deleted, and types cannot be modified. This makes sure that the pointer to this object is also valid after an online change.

For this reason, the __NEW operator can be applied only to function blocks from libraries and function blocks with the attribute “enable_dynamic_creation”. If the interface of this kind of function block is changed, then CODESYS issues an error message.

Attention

Two tasks should not call __NEW at the same time. Either you use a semaphore (SysSemEnter) or comparable method to prevent any concurrent calling of __NEW, or you use __NEW in one tasks only (recommended).

You can use a semaphore (SysSemEnter) to prevent two tasks from allocating memory at the same time. As a consequence, the extensive use of __NEW causes higher jitter.

Examples

With scalar type:

TYPE DUT :
    STRUCT
     a,b,c,d,e,f : INT;
    END_STRUCT
END_TYPE

PROGRAM PLC_PRG
VAR
\ pDut : POINTER TO DUT;
\ bInit : BOOL := TRUE;
\ bDelete : BOOL;
END_VAR

IF (bInit) THEN
\ pDut := __NEW(DUT);
\ bInit := FALSE;
END_IF
IF (bDelete) THEN
\ __DELETE(pDut);
END_IF

With function block

{attribute 'enable_dynamic_creation'}
FUNCTION_BLOCK FBDynamic
VAR_INPUT
    in1, in2 : INT;
END_VAR
VAR_OUTPUT
    out : INT;
END_VAR
VAR
\ test1 : INT := 1234;
\ _inc : INT := 0;
\ _dut : POINTER TO DUT;
\ neu : BOOL;
END_VAR

out := in1 + in2;

PROGRAM PLC_PRG
VAR
\ pFB : POINTER TO FBDynamic;
\ loc : INT;
\ bInit : BOOL := TRUE;
\ bDelete : BOOL;
END_VAR

IF (bInit) THEN
\ pFB := __NEW(FBDynamic);
\ bInit := FALSE;
END_IF

With array:

PLC_PRG(PRG)
VAR
\ bInit: BOOL := TRUE;
\ bDelete : BOOL;
\ pArrayBytes : POINTER TO BYTE;
\ test : INT;
\ parr : POINTER TO BYTE;
END_VAR

IF (bInit) THEN
\ pArrayBytes := __NEW(BYTE, 25);
\ bInit := FALSE;
END_IF

IF (bDelete) THEN
\ __DELETE(pArrayBytes);
END_IF