Wednesday, May 2, 2007

How to do pointers in Visual Basic

How to do pointers in Visual Basic - The Code Project - VB / VBScript

Here is a simple and not complete implementation of a linked list. (On the form put a Command button named Command1)


Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory"_
(Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function GetProcessHeap Lib "kernel32" () As Long
Private Declare Function HeapAlloc Lib "kernel32" _
(ByVal hHeap As Long, ByVal dwFlags As Long, _
ByVal dwBytes As Long) As Long
Private Declare Function HeapFree Lib "kernel32" _
(ByVal hHeap As Long, ByVal dwFlags As Long, _
lpMem As Any) As Long
Private Declare Sub CopyMemoryPut Lib "kernel32" Alias _
"RtlMoveMemory" (ByVal Destination As Long, _
Source As Any, ByVal Length As Long)
Private Declare Sub CopyMemoryRead Lib "kernel32" Alias _
"RtlMoveMemory" (Destination As Any, _
ByVal Source As Long, ByVal Length As Long)

Dim pHead As Long
Private Type ListElement
strData As String * 255 '==255 * 2=500 bytes vbStrings are UNICODE !
pNext As Long '4 bytes
'pointer to next ; ==0 if end of list
'----------------
'total: 504 bytes
End Type

Private Sub CreateLinkedList()
'add three items to list
' get the heap first
Dim pFirst As Long, pSecond As Long 'local pointers
Dim hHeap As Long
hHeap = GetProcessHeap()
'allocate memory for the first and second element
pFirst = HeapAlloc(hHeap, 0, 504)
pSecond = HeapAlloc(hHeap, 0, 504)
If pFirst <> 0 And pSecond <> 0 Then
'memory is allocated
PutDataIntoStructure pFirst, "Hello", pSecond
PutDataIntoStructure pSecond, "Pointers", 0
pHead = pFirst
End If
'put he second element in the list
End Sub

Private Sub Command1_Click()
CreateLinkedList
ReadLinkedListDataAndFreeMemory
End Sub

Private Sub PutDataIntoStructure(ByVal ptr As Long, _
szdata As String, ByVal ptrNext As Long)
Dim le As ListElement
le.strData = szdata
le.pNext = ptrNext
CopyMemoryPut ptr, le, 504
End Sub

Private Sub ReadDataToStructure(ByVal ptr As Long, _
struct As ListElement)
Dim le As ListElement
CopyMemoryRead le, ptr, 504
struct.strData = le.strData
struct.pNext = le.pNext
End Sub

Private Sub ReadLinkedListDataAndFreeMemory()
Dim pLocal As Long
Dim hHeap As Long
Dim le As ListElement
Dim strData As String
pLocal = pHead
hHeap = GetProcessHeap()
Do While pLocal <> 0
ReadDataToStructure pLocal, le
strData = strData & vbCrLf & le.strData
HeapFree hHeap, 0, pLocal
pLocal = le.pNext
Loop
MsgBox strData
End Sub

Private Sub Form_Load()

End Sub