My question is: what are the benefits of using pointers and reference to?
I am new to codesys and in my previous job, I programmed in TIA portal (Siemens) and Sysmac Studio (Omron) and never came across pointers or something similar. I think I understand how they work but not sure when I should be using them myself.
For example, I just received a function block from a supplier:
Why don't they just have an array for input and output?
CodePudding user response:
First of all, if you have ever used the VAR_IN_OUT
declaration, then you have already used references, since that is equivalent to a VAR
with REFERENCE TO
.
As for the uses, there are mainly 4 that I can think of right now:
Type Punning, which you can also achieve using a
UNION
, but you may not want to have to create a union for every single reinterpretation cast in your code.TL; DR: To save memory and copy execution time. Whenever you pass some data to a function/function block, it gets copied. This is not a big problem if your PLC has enough CPU power and memory, however if you are dealing with especially huge data on a low end PLC, then you may either exceed real time execution constraints, or run out of memory. When you pass a pointer/reference however, no matter how big the data is only the pointer/reference gets copied and passed, which is 4 bytes in 32 bit system, and 8 bytes in a 64 bit one.
In C style languages you'd use pointers/references when you want a function to return multiple values without the hassle of creating a custom structure every time. You can do the same here to, however in CODESYS function can have multiple outputs, for example:
VAR_OUPUT
out1 : INT; (*1st output variable *)
out2 : INT; (*2nd output variable *)
//...
END_VAR
- And finally, as I mentioned at the very beginning, when you want to pass some data that needs to be modified in the function itself, in other words, where you can use
VAR_IN_OUT
you can also use pointers/references. One Special case where you will have to use a pointer is if you have aFunction Block
that receives some data in theFB_Init
(initialization/construction) function and stores it locally. In such case you would have a pointer as a local variable in the function block, and take the address of the variable in theFB_Init
function. Same applies if you have a structure that needs to reference another structure or some data.
PS. There are probably some other uses I missed. One of the main uses in other languages is for dynamic memory allocations, but in CODESYS this is disabled by default and not all PLCs support it, and hardly anyone (that I know) uses it.