plctwincatststructured-textiec61131-3

How to pass variable type as an argument to an function in IEC61131-3 structured text (TwinCAT3)?


This is what I would like to have (this is a constructor for FB object):

METHOD FB_init : BOOL
    VAR_INPUT
        bInitRetains : BOOL;
        bInCopyCode : BOOL;

        //My variables:
        typeOfVariable : TYPE; // This obviously doesn't work 
    END_VAR

size := 1;
myArray := __NEW(typeOfVariable, size); // Create dynamic array with 'typeOfVariable' variables.

END_METHOD

This is the code for it:

myArray := __NEW(REAL, 10); //Create array with type REAL variables with the size of 10

Solution

  • OK, here a small example how you could tackle this problem:

    Create an Enum first:

    TYPE E_Type :
    (
        eNO_TYPE := 0,
        eINT,
        eREAL
    );
    END_TYPE
    

    Use it in a switch case:

    METHOD createArray : POINTER TO BYTE
    VAR_INPUT
        eType : E_Type;
        size : UINT;
    END_VAR
    
    CASE eType OF
        eINT:
            //Remember to __DELETE
            createArray := __NEW(INT, size);
        eREAL:
            createArray := __NEW(REAL, size);
    END_CASE
    

    Check for Null-Pointer and remember to __Delete when you don't need the array anymore.