Page 1 of 1

How to pass by reference ByRef

Posted: Wed Jan 29, 2014 12:46 am
by TeraByte
I have researched the forums and have seen many ways to pass a value by reference and am now confused as the which is the best method. In VisualBasic 6 and PowerBasic you can specify the keyword "ByRef", so I am simply looking for the equivalent way in PureBasic. :D

The following works, but is it the "proper" way? I just want something easy and reliable.

ProcedureDLL DoubleByRef(*num1.Double)
*num1\d = 17
EndProcedure

Define d1.d = 7

DoubleByRef( @d1 )

; Now d1 = 17

Re: How to pass by reference ByRef

Posted: Wed Jan 29, 2014 1:06 am
by skywalk
That's what I use.

Re: How to pass by reference ByRef

Posted: Wed Jan 29, 2014 3:23 am
by Demivec
TeraByte wrote:The following works, but is it the "proper" way? I just want something easy and reliable.
Yes, it's the proper way.

Also, if you are dealing with lists/maps/arrays you would pass them by reference as parameters of a procedure by using the required word List/Map/Array before them, instead of using a pointer (i.e. 'Procedure blah(List myList()').

Re: How to pass by reference ByRef

Posted: Wed Jan 29, 2014 12:34 pm
by luis
Just wanted to mention you can also receive a "void" pointer instead of a structured one and use the right Poke variant to stuff data in it.

Code: Select all

ProcedureDLL DoubleByRef(*num1)
PokeD(*num1, 17.0)
EndProcedure

Define d1.d = 7.0

DoubleByRef( @d1 )

Debug d1
The structured way it's better.
More efficient (no function call, less code) and less error prone, but this can be useful (mostly because easy to use) in some situations instead of using pointers math.

Re: How to pass by reference ByRef

Posted: Wed Jan 29, 2014 3:12 pm
by BorisTheOld
TeraByte wrote:The following works, but is it the "proper" way? I just want something easy and reliable.
Yes, it's the proper way, but you might want to look at modifying how you do it.

We're in the process of a major conversion from VB, PowerBasic, MASM, and COBOL. Almost all procedure calls in these languages were ByRef, so it was messy for us to do a direct conversion to PB.

Our solution was to wrap all our data in structures. Each module in our code contains a structure which holds all the data. By passing the structure to procedures in the module, all the module data can be accessed ByRef. This is a simple technique that avoids messing with individual fields.

Since this is essentially how classes work, we took it one step further and implemented OOP by adding an interface to each module. Also, where possible, we changed ByRef to ByVal, and used ProcedureReturn.

The technique is probably over-kill for this small example, but it works well for our 500,000 lines of code.

Code: Select all

Structure MyData
  Var1.i
  Var2.s
EndStructure

Procedure Test(*Me.MyData)
  *Me\Var1 = 99
  *Me\Var2 = "abc"
EndProcedure

Me.MyData

Test(@Me)

Debug Me\Var1
Debug Me\Var2