Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2021-01-21 09:44:06

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
  • In this method I would pass to the parameter typeOfVariable for example REAL and the method would create array of REAL variables with size 1.
  • I need to know what type I declare typeOfVariable so it can store the data about type of another variable.

  • Working example is the __NEW() method for dynamically creating array.

  • This method takes in a argument such as REAL or INT.

This is the code for it:

myArray := __NEW(REAL, 10); //Create array with type REAL variables with the size of 10
Questioner
Jakub Szlaur
Viewed
0
Filippo Boido 2021-01-22 02:53:30

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.