如何将变量类型作为参数传递给 IEC 61131-3 结构化文本 (TwinCAT 3) 中的函数?

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

这就是我想要的(这是 FB 对象的构造函数):

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

这是它的代码:

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

好的,这是一个如何解决这个问题的小例子:

首先创建一个枚举:

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

在开关盒中使用它:

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

检查 Null 指针并记住 __Delete 当您不再需要该数组时。

令我惊讶的是(意外地)我发现有一个名为 ETcloEcPredictDataType 的文件包含以下代码:

{attribute 'TcTypeSystem'}
{attribute 'signature_flag' := '33554432'}
{attribute 'checksuperglobal'}
{attribute 'show'}
{attribute 'no-analysis'}

    {attribute 'GUID' := '6FFE9C73-9040-49AE-8731-5485B8A3A604'}
{attribute 'Namespace' := 'IO'}
TYPE ETcIoEcPredictDataType : (_SINT:=1, _USINT:=2, _INT:=3, _UINT:=4, _DINT:=5, _UDINT:=6, _LINT:=7, _ULINT:=8, _REAL:=9, _LREAL:=10) UDINT;
END_TYPE

Note that I didn't even have to include this file. I just written down _REAL clicked on it and choose Go to definition. Then it opened the ETcloEcPredictDataType file.


因此,根据 的回答,您可以使用此 CASE 语句创建函数:

//_SINT:=1, _USINT:=2, _INT:=3, _UINT:=4, _DINT:=5, _UDINT:=6, _LINT:=7, _ULINT:=8, _REAL:=9, _LREAL:=10
CASE _type OF
    1: myArray := __NEW(SINT, size);
    2: myArray := __NEW(USINT, size);
    3: myArray := __NEW(INT, size);
    4: myArray := __NEW(UINT, size);
    5: myArray := __NEW(DINT, size);
    6: myArray := __NEW(UDINT, size);
    7: myArray := __NEW(LINT, size);
    8: myArray := __NEW(ULINT, size);
    9: myArray := __NEW(REAL, size);
    10: myArray := __NEW(LREAL, size);
END_CASE

并调用FB构造函数如下:

array : dynamicArray(_REAL);

PLC_ReadSymInfoByName() 可以对功能块执行此操作, 属性 'instance-path' > PLC_ReadSymInfoByName > “FB_Test”

也可以用结构来做到这一点。 ST_Real:fValue:实数; eTypeOf : E_Type:= E_Type.Real;