Roald87 / roald87.github.io

Mostly cooking and coding in TwinCAT.
https://cookncode.com
MIT License
4 stars 2 forks source link

twincat/2021/04/20/overloading-with-extended-structs #38

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

'Overloading' functions with extended structs

I was wondering if overloading functions in TwinCAT was possible, but I found out that this is not the case. I did however realize that overloading is possible using a few work-arounds. In this article I’ll show how to mimic this behavior with extended structs.

https://cookncode.com/twincat/2021/04/20/overloading-with-extended-structs.html

Daniel-Kurth commented 1 year ago

Thanks for the useful write-up - even though I only skimmed it. I'd like to add two points to the entire thing:

One, from my short testing, this overloading also works with Function Blocks .

Two, the overloading does not work when the extended data type is part of an array. For the above example, this would mean "aPoints2 : ARRAY [0..10] OF TimePoint" won't work with a function Length - obviously this has to be adjusted to handle arrays.

Roald87 commented 1 year ago

@Daniel-Kurth thanks for the additions! Can you give an example for the function block case?

Daniel-Kurth commented 1 year ago

Sure:

FUNCTION_BLOCK FB_length
VAR_INPUT
    point : Point;
END_VAR
VAR_OUTPUT
    Length :LREAL;
END_VAR
VAR
END_VAR

Length := SQRT(EXPT(point.x, 2) + EXPT(point.y, 2));
Roald87 commented 1 year ago

@Daniel-Kurth ah yes like that. I thought you meant something like using a FB_Child EXTENDS FB_Base instance as an input for a function block which takes a FB_Base.

FUNCTION BLOCK FB_Example
VAR_INPUT
 fbBase : FB_Base;
END_VAR

-----

PROGRAM MAIN
VAR
 fbChild : FB_Child;
 fbExample : FB_Example;
END_VAR

fbExample(fbBase:=fbChild);