How to share arrays among cogs
Dave Matthews
Posts: 93
I have a 500 word array defined in my top object (controls), from which start another object (Test Object), passing the address of the data array to the second object which then runs a new cog. Is it possible to refer to the address of the array in the second object globally? In the example code of Test Object, the routine called 'second' will not compile, as expected. How can I do this without passing the Data1 variable from method to method throughout an object?
controls.spinTest Object.spin
controls.spinTest Object.spin

Comments
To make the address passed to the Start method global define the variable in your VAR section.
And assign the value passed as a parameter to the variable.
PUB Start(Data1, datastack) : success Stop dataPtr := Data1 success := (cog := cognew(Main, datastack) +1)You then no longer need to pass "Data1" to the main menu since it can now use the global variable.
You can use "dataPtr" in your methods like this:
PUB Main | i pst.Start (115_200) Repeat i from 0 to 25 PST.newline PST.dec(i) PST.str(string (" : ")) PST.hex(byte[dataPtr][i],2) Second PUB Second | i Repeat i from 0 to 25 PST.newline PST.dec(i) PST.str(string (" : ")) PST.hex(byte[dataPtr][i],2)Alternatively, you get by without the global variable if you pass the address received by "Main" to "Second".
PUB Main (Data1) | i pst.Start (115_200) Repeat i from 0 to 25 PST.newline PST.dec(i) PST.str(string (" : ")) PST.hex(byte[Data1][i],2) Second(Data1) PUB Second(Data1) | iOf course the variable doesn't need to be named "Data1". The follow code would work the same way.
PUB Main (dataPtr) | i pst.Start (115_200) Repeat i from 0 to 25 PST.newline PST.dec(i) PST.str(string (" : ")) PST.hex(byte[dataPtr][i],2) Second(dataPtr) PUB Second(localPtr) | i ' use "localPtr" where "Data1" had been used in this method.You can pass addresses back to the parent method by using the return value of a method. You could add a method just to pass the address.
For example, I often include the following method in my programs.
The buffer "fileName" is declared in a DAT section like this.
Of course you would have the buffer contain whatever data you like. The parent object could modify the buffer once it had the address.