Date: 02-16-2022
Return to Index
created by gbSnippets
'Pointers:
' - are variables
' - hold 32-bit address of code/data located elsewhere in memory (points to that location)
'Two formats to declare a pointer variable
Dim i as Integer PTR
Dim i as Integer POINTER
'Integer pointers
Dim i as Integer PTR
Dim j as Integer, k as Long
j = 42
i = VarPTR(j)
k = i 'k gets the 32 bit address
k = @i 'k gets the value 42
'String pointers
Dim sP as String PTR, i as Long
Dim sName as String, sTemp as String
sP = StrPTR(sName)
sName = "Gary"
i = sP 'i gets the 32 bit address
sTemp = @sp 'sTemp gets the value "Gary"
'Speed is a major reason for using pointers
'Example - scan all the characters in a buffer, replacing all upper case "A"s with
'lower case "a"s. The pointer version of the code might look something like this:
'Pointer Method
Sub Lower(zStr AS String)
Dim s AS BYTE PTR, ix AS INTEGER
s = StrPTR(zStr) ' Access the dynamic string directly
For ix = 1 TO Len(zStr)
If @s = 65 Then @s = 97 ' "A" -> "a"
Incr s
Next
End Sub
'Traditional Method
Sub Lower(zStr AS String)
Dim s AS BYTE PTR, ix AS INTEGER
s = StrPTR(zStr) ' Access the dynamic string directly
For ix = 1 TO Len(zStr)
If Mid$(zStr, ix, 1) = Chr$(65) Then Mid$(zStr,ix,1) = Chr$(97) ' "A" -> "a"
Incr s
Next
End Sub
'Both get the job done, but the Pointer method avoids all of the Mid$
'code and about 10X faster than the traditional method
'UDT elements can be pointers but not the UDT variable itself
Type NameRec
Last AS String * 20 ' Last name
First AS String * 20 ' First name
Nxt AS NameRec PTR ' Pointer to next record
Prv AS NameRec PTR ' Pointer to previous record
End Type
Dim Rec AS NameRec
Rec.@Nxt ' next record
Rec.@Prv ' previous record
'gbs_00011
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm