Creat an array in CoDeSys with changeable size - arrays

I am working on a moving average algorithm to analyze a sensor values and the values are stored in an Array. BUT, the length of Array is variabla (depends on speed of one motor).
how can I Creat an array in CoDeSys with changeable size.
It's wrong to define Array so :
Name: ARRAY[1...SpeedValue] OF INT ;

I am sorry to tell you that there is no changeable size for arrays in Codesys V2/V3. The general explanation is that there is no Dynamic Memory Allocation available in a PLC because Dynamic Memory Allocation is considered to be too unreliable.
Your only choice is to define an array with a constant ARRAY[1..N_MAX_SPEED_VALUE] and just use the array until SpeedValue
VAR
arrnValues : ARRAY[1..N_MAX_SPEED_VALUE] OF INT;
END_VAR
VAR CONSTANT
N_MAX_SPEED_VALUE : INT := 100; (*Max Array Size*)
END_VAR
For myself I am really bugged by this limitation. I already requested a feature many times, to define arrays like ARRAY[*], have keywords for start and end and define the actual start and end size when instantiating. This has nothing todo with dynamic memory allocation, because size is defined at compile time.

I would recomend you the following post.
https://stefanhenneken.wordpress.com/2016/09/27/iec-61131-3-arrays-with-variable-length/
Stefan describes step by step what is possible to do with variable length arrays.
I wouldn't recommend what Felix sugested because:
First: You never want to have variable scan times.
Second: If for some reason, lets just say something broke and the SpeedValue that you want to be the upper bound of your array is impossible to reach, then you either have a deadlock or a bad output without really knowing if something is wrong

Dynamic array is possible with the help of pointers and operators "__NEW", "__DELETE":
VAR
arrnValues : POINTER TO INT;
SpeedValue : UDINT;
END_VAR
SpeedValue := 100;
arrnValues := __NEW(INT, SpeedValue);
__DELETE(arrnValues);
You must also activate dynamic memory allocation in the Application Properties:
Application Build Options

Related

When to use slice instead of an array in GO

I am learning GO. According to documentation, slices are richer than arrays.
However, I am failing to grasp hypothetical use cases for slices.
What would be use case where one would use a slice instead of array?
Thanks!
This is really pretty elementary and probably should already have been covered in whatever documentation you're reading (unless it's just the language spec), but: A Go array always has a fixed size. If you always need 10 things of type T, [10]T is fine. But what if you need a variable number of things n, where n is determined at runtime?
A Go slice—which consists of two parts, a slice header and an underlying backing array—is pretty ideal for holding information needed to access a variable-sized array. Note that just declaring a slice-header variable:
var x []T
doesn't actually allocate any array of T yet: the slice header will be initialized to hold nil (converted to the right type) as the (missing) backing array, 0 as the current size, and 0 as the capacity of this array. As a result of this, the test x == nil will say that yes, x is nil. To get an actual array, you will need either:
an actual array, or
a call to make, or
use of the built-in append or similar (e.g., copy, append hidden behind some function, etc).
Since the call to make happens at runtime, it can make an array of whatever size is needed at this point. A series of calls to append can build up an array. Note that each call to append may have to allocate a new backing array, or may be able to extend the existing array in-place, depending on what's in the capacity. That's why you need x = append(x, elem) or x = append(x, elems...) and not just append(x, elem) or append(x, elems...).
The Go blog entry on slices has a lot more to say on this. I like this page more than the sequence of pages in the Go Tour starting here, but opinions vary.

Convert array to array of const in Delphi

I am looking for a simple and ideally general (or using generics) way to convert an array to an array of const (=array of TVarRec). My specific case is that I have an array of Variant and want to pass it to the Format() function.
This is what I've found so far, but it looks hackish to me:
function MyFormat(const Fmt: string; const Args: TArray<Variant>): string;
var
A: array of TVarRec;
I: Integer;
begin
SetLength(A, Length(Args));
for I:= Low(Args) to High(Args) do begin
A[I].VType:= vtVariant;
A[I].VVariant:= #Args[I];
end;
Result:= Format(Fmt, A);
end;
It seems to work. Is it safe?
Could it be done shorter, better, faster, or can I use something ready instead? :)
Just some additional thoughts and fun facts:
System.Rtti.TValue recently became my friend. However, it seems it is missing a feature here. I am able to read my array using TValue.From(), but it seems there is no way to get it out as array of TVarRec. There is a wonderful TValueArrayToArrayOfConst, but it doesn't really help, because I had to construct an array of TValue first, which is different from an array stored in a single TValue... :(
At least TValue is able to output a single element as TVarRec, so I thought I could create a generic converter for all types of arrays. But...
Would you think this works?
for I:= Low(Args) to High(Args) do A[I]:= TValue.From(Args[I]).AsVarRec;
It compiles, but TValue's memory is released after use, and since TVarRec.VVariant is a pointer, it then points to some old location which is overridden on next cycle.
Your function is safe and fast. It only allocates a small memory array A[], and passes all values by reference. I can't think on anything faster - without being premature optimization. I may only do some refactoring to reuse the TArray<variant> into TArray<TVarRec> conversion routine.
Using TValue.From().AsVarRec will definitively be slower, if your input is indeed a TArray<Variant>.
About TVarRec dandling references, you are right: those structures are just simple pointers on the stack, with no allocation, so all the referred variables should be available during the function call. So if you use a TArray<TVarRec> local conversion, you should ensure that the TArray<variant> is still allocated when calling the format() function.
A straight forward and short solution (in code). If your formatstring (fmt) and array of values (sa) are unknown.
setlength(sa,5); // or more
result := format(fmt,[sa[0],sa[1],sa[2],sa[3],sa[4]];

how to construct an array with specific element size in python3?

you might ask "why don't you just use C?",
but I would like to try constructing an array
with specific element size using python 3, is that possible?
I know bytearray() but it's limited to one byte per element, is there a more flexible function?
also, is there any equivalent statement in python 3 to "sizeof(int)" in C?
I am not talking about sys.getsizeof(int) since it gives me the bytesize of the whole int class
x = [None]*10
This will initialize a list with size 10, but you can also take a look at arrays from the numpy module. This will also have lots of other optimization in it too.
I don't have much experience with your memory problem, but maybe this code will help? http://code.activestate.com/recipes/546530/

Should array's length be set to zero after use?

I'm wondering if setting Delphi's array's length to 0 after use is a correct practice or not.
var
MyArray : array of TObject;
begin
SetLength(MyArray, N);
// do something with MyArray (add items and use it..)
SetLength(MyArray, 0);
end;
Is there a reason why I should set length to 0?
Assuming that MyArray is a local variable then there is no reason at all to finalise the variable in the code presented. As soon as the variable leaves scope, it will be finalised. There's nothing to be gained by doing so explicitly.
Sometimes however, you have a variable whose scope extends significantly longer than your use of the array. In those scenarios it can be useful to finalise the variable as soon as you have finished with it so that the memory is returned.
Personally I would prefer
MyArray := nil;
or
Finalize(MyArray);
which in my opinion more readily jump out as finalisation statements. Your
SetLength(MyArray, 0);
can look like you are allocating when skimming the code.
Dynamic arrays are automatically freed when nothing is referencing it.
I would prefer the following method if you need to do this manually. This looks clear to me than other methods.
MyDynamicArray = nil;
It sets the natural environment of zero reference and let the memory manager to free it in due course.

How Swift implement Array's copy-on-write behavior?

After watching build better apps with value type . In the photoshop example they made, they said that
the only thing that gets copied in the two instances of that diagram are the tiles that contain the person's shirt. So even though I have two distinct documents, the old state and the new state, the only new data that I have had to consume as a result of that is the tiles contained in this person's shirt.
So I begin to wonder how would these two array in memory looks like. So I do a little experiment.
struct Test {
var i: Int
var j: Int
}
var valueArray = [Test(i: 1, j: 9), Test(i: 2, j: 7)]
var valueArray2 = valueArray
When I print valueArray and valueArray2's address, they are not the same.
"Maybe they implement this by store pointer in array?"
But when I print memory content using lldb , they are actually just 4 Int (1,9,2,7).
So I am confused, I haven't even change the array yet. And they seems to make a copy of entire array? So where did I misunderstand?
The function I used to print struct's address is by using the method provided by #nschum in this question.
func address(o: UnsafePointer<Void>) {
let addr = unsafeBitCast(o, Int.self)
print(NSString(format: "%p", addr))
}
This is not a duplicate question of this question. I am asking about language feather and the other one is about programming skill.
Okay, I did many experiment and finally figured out.
We can's use & to get array address because once we do that , Swift will copy the array to better interact with C, use & get object's address that adjacent to array and do the math instead. Or use lldb instruction frame variable -L
The whole Array is copied once any of it's value element changed.
Actual value element of Array is allocated at heap.
Swift also did a lot of optimization for Array whose element is class.
Swift is awesome.
I actually write my first blog for this.
After your comments and getting a better understanding if this, I loaded it up in a playground and it seems to be working as expected
original answer for reference
The thing to remember with this is that structs are basically chunks of data in memory. When you create the valueArray, a chunk of memory is being set to value it's assigned
When you create valueArray2, you're creating a new instance of the struct, which means it will have a brand new chunk of memory, and you're then setting the value of that new chunk of memory to the same value of the chunk of memory from the valueArray. This results in a copy of the data in two different memory locations.
This is in contrast to an object, in which case valueArray would be a pointer to a chunk of memory, and when you create valueArray2 it would be creating a new pointer to the same chunk of memory.

Resources