PDA

View Full Version : Varptr() as a function-parameter?



ReneMiner
20-02-2013, 18:10
I want to assign values inside a function to a udt like this example



Type myUDT
A as Dword
B as Long
C as Double
End Type

Dim foo as myUDT
Dim bar as myUDT

'...
' ...from different calls with different var-names i want to calculate something
' and place the "result" into bar or foo

calc(1,2,varPtr(bar)) ' shall fill in bar
calc(2,1,varPtr(foo)) ' and into foo this time

' now how set I up the subs parameters?

Sub calc(byval X as long , byval Y as long, byref myPtr as myUDT) ' ???

' now calc for example the result for .A, .B and .C

Poke (Dword, varPtr(myPtr), X + Y)
Poke(Long, varPtr(myPtr)+4, X + Y * 123)
Poke(Double, varPtr(myPtr)+8), 1/(X+Y))

End Sub

so basically I want to fill out any variable that is dimensioned as myUTD somehow with the sub.
I need the pointer to the first element of that UDT, but how do I get it as a Functions-Parameter so i can call it that way?

Poking is just a guess, maybe there is an easier way as this?


myPtr.A = X + Y
myPtr.B = X + Y * 123
myPtr.C = 1/(X+Y)

Petr Schreiber
20-02-2013, 21:34
Hi Rene,

in thinBASIC, for many situations you don't need to touch the pointers at all. You can achieve what you need with simple ByRef and direct passing of the variable:


Uses "Console"

' -- User defined type
Type myUDT
A As DWord
B As Long
C As Double
End Type

Function TBMain()

' -- Two variables
Dim first As myUDT
Dim second As myUDT

' -- When using BYREF, pass just the name directly
calc(1, 2, first)
calc(2, 1, second)

' -- Printing out the contents of the UDT
PrintL "first:"
PrintL UDT_ElementsData_Join(first, $CRLF)
PrintL

PrintL "second:"
PrintL UDT_ElementsData_Join(second, $CRLF)
PrintL

WaitKey
End Function

Sub calc(ByVal X As Long , ByVal Y As Long, ByRef myVariable As myUDT)

myVariable.A = X + Y
myVariable.B = X + Y * 123
myVariable.C = 1 / ( X + Y )

End Sub



Petr

ReneMiner
20-02-2013, 21:58
thank you.
That easy!

sometimes it's like I don't find the forest whithin all those trees :)