Search code examples
twincatstructured-text

Strings in FB_init


Is there a way to declare a undefined length string as a constructor or a work around?

I need to write a log file for a function block. The file name needs to be declared in the FB declaration but there are compiler errors which don't allow me to use strings as constructors.

FUNCTION_BLOCK FB_LogFile
VAR
    sfileName : REFERENCE TO T_MaxString;
END_VAR

METHOD FB_init : BOOL
VAR_INPUT
    bFileName: REFERENCE TO T_MaxString;
END_VAR    
THIS^.sfileName:=sFileName;
PROGRAM Main
VAR
    LogTest:FB_LogFile(sFileName:='c:/config/config.csv';
END_VAR
LogTest();

Solution

  • To answer the question you asked, If you want to pass in a string of an undefined length then the generally accepted method is using a pointer to the dataspace occupied by the string, and the length of the string. Specifically:

    VAR_INPUT
        pString : POINTER TO BYTE; // Pointer to the first char of a string
        nString : UDINT; // Length of the string
    END_VAR
    

    In regard to other points raised by your code, I believe the error you are specifically referring to is due to your reference handling. When using references it is necessary to understand that they handle dereferencing differently to pointers. To quote InfoSys:

    refA REF= stA; // represents => refA := ADR(stA);  
    refB REF= stB1; // represents => refB := ADR(stB1);
    refA := refB; // represents => refA^ := refB^; 
    (value assignment of refB as refA and refB are implicitly dereferenced) 
    refB := stB2;    // represents => refB^ := stB2;
    (value assignment of stB2 as refB is implicitly dereferenced)
    

    This applies to FB_Init as well so your code should actually read:

    FUNCTION_BLOCK FB_LogFile
    VAR
        rFilePath: REFERENCE TO T_MaxString;
    END_VAR
    
    METHOD FB_init : BOOL
    VAR_INPUT
        rLocalPath : REFERENCE TO T_MaxString;
    END_VAR    
    rFilePath REF= rLocalPath;