I've taught myself how pointers work in C++ and really liked them. Now I want to learn them in bmax. I've gotten the basics however run into some problem when trying to pass and object by pointer. According to the documentation you may pass objects by pointer and the index of the pointer passes the field variable mapped to that index. With that said, I don't understand why this code is not working...
' demonstrates pointers
SuperStrict
'///////////////////////////////////////////
' first we test passing an int by pointer...
'///////////////////////////////////////////
'create a test int and assign it value
Global the_number:Int = 1998
'create out int pointer, use varptr to assign it to the_number
'a pointer must point to a memory location, varptr does this
Global pointer:Int Ptr = Varptr(the_number)
'finally print the value pointed to by pointer
rem
since a pointer points to a point in memory
we want where it is pointing. To do this, we just
want the index it is pointing to. This means that we
want memory index 0, the starting point of the pointed
to memory.
endrem
'recall the value of the pointed to memory
Print(pointer[0])
'///////////////////////////////////////////
'test passing an array by pointer...
'///////////////////////////////////////////
Global array:Float[] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
' arrays are not directly supported, however they can still be passed
Global array_pointer:Float Ptr = Varptr(array[0])
rem
arrays are stored in a linear fashion, so if we pass the memory
location of the first index, we may iterate throught the entire
array!
endrem
For Local i:Int = 0 To array.dimensions()[0] - 1
Print(array_pointer[i])
Next
'///////////////////////////////////////////
'test passing a complex object by pointer...
'//////////////////////////////////////////
rem
since we do not have direct object pointers in Blitzmax,
we are forced to use byte pointers! In this case,
the first index of the pointer is the first field value
of the object in question. Lets try it
endrem
rem from the docs
BlitzMax will automatically convert any pointer type to a byte pointer
for you. In addition, objects and arrays may be assigned to byte pointers.
In the case of objects, the pointer will contain the address of the
first field of the object. In the case of arrays, the pointer will
contain the address of the first element of the array. Be very careful
when assigning objects to pointers, as there is a danger that the garbage
collector will 'reclaim' the object before you have finished with the
pointer! It is recommended that you use GCSuspend and GCResume around code
that converts objects to pointers.
endrem
Type human
Field age:Byte = 22, name:String = "Mr. Burnside"
End Type
GCSuspend()
Global ryan:human = New human
Global human_pointer:Byte Ptr = Varptr(ryan)
'print his attributes
Print(human_pointer[0])
Print(human_pointer[1])
GCResume()