How to implement an interface (IElement)?

drml
2024-07-19
2024-07-22
  • drml - 2024-07-19

    I'm struggling with the implementation of the IElement interface (in the ElementCollections library), which I will use to create a SortedList. I created a class (FB) "Device" that implements this interface and that has a "Priority" property that I want to use in order to compare the devices in my implementation of the ElementCompareTo method. Unfortunately, the IElement.ElementCompareTo method needs an IElement as an input, which doesn't know about the "Priority" property of "Device". I tried to define the input itfElement as a Device, but then it doesn't want to compile, because the type in the implementation doesn't match the interface.

     
  • TimvH

    TimvH - 2024-07-22

    See:
    https://forge.codesys.com/prj/codesys-example/element-collect/home/Home/
    This contains an application "OnlineChangeSafeLinkedListExample".

    What you should do is create a new interface which has your "Priority" property.
    Then your FB should extend the base element function block and implement your own interface:
    E.g. FUNCTION_BLOCK MyElement EXTENDS COL.LinkedListElementBase IMPLEMENTS I_MyInterface

    Then the __QUERYINTERFACE does the magic to check if your "element" also implements your interface.

    Something like this:

    // Compares this element with itfElement.
    // Returns 0 if the elements are equal, < 0 if the element is less than itfElement, 
    // > 0 if the element is greater than itfElement.
    // This method will be called from sorted collections (e.g. |COL.SortedList|) to sort the elements.
    // IMPORTANT: The underlying value to be compared with MUST NOT be changed during the lifecycle of the object.
    METHOD ElementCompareTo : INT
    VAR_INPUT
        (* The element to compare*)
        itfElement  : COL.IElement;
    END_VAR
    VAR
        itfIntElement : I_MyInterface;
        xResult : BOOL;
    END_VAR
    
    // We use integer iInt1 for sorting.
    xResult := __QUERYINTERFACE(itfElement, itfIntElement);
    IF xResult THEN
        IF iInt1 < itfIntElement.Priority THEN
            ElementCompareTo := -1;
        ELSIF iInt1 > itfIntElement.Priority THEN
            ElementCompareTo := 1;
        ELSE
            ElementCompareTo := 0;
        END_IF
    ELSE
        ElementCompareTo := -1;
    END_IF 
    
     

Log in to post a comment.