UnderwareDESIGN

PlayBASIC => Resources => Source Codes => Topic started by: kevin on September 13, 2013, 01:26:15 AM

Title: User Defined Type Pointer Example
Post by: kevin on September 13, 2013, 01:26:15 AM
 User Defined Type Pointer Example

      This is little example shows the life cycle of a user defined typed pointer,  they're basically the same as typed variable, except rather than have PlayBASIC maintain a container (a safe house) around the type, pointer deals with an address to an actual location in memory.   So the pointer is pointing at whatever you set it to.   In the example, we use NEW to allocate a chunk of memory that represents our type fields.   Once that's done we can read /write to the fields just like a regular type.  There's a few differences, namely if you used NEW to allocate some memory, then it expects you to FREE this memory when you no longer need it.        

[pbcode]

      Type PlayerInfo
            a
            b#
            c$
      EndType


      // Declare Me as UDT pointer
      dim me as PlayerInfo pointer

      // allocate the structure and store it's address in the ME pointer
      Me = new PlayerInfo


      // Display what's in the fields initially, they should all be empty and set to zero
      Display(me)
      
      // Fill the fields in with some bogus info.
      me.a= 1111
      me.b = 123.456
      me.c = "Some string"
      
      // Show the filled in contents
      Display(me)


      // Release All the fields in this structure.  This is like setting each field to zero. 
      me.PLayerInfo= null
      

      // Show the now empty fields again (set to zero)
      Display(me)


      // Free will clear all the fields in this structure, Delete the memory and set the pointer
      // to zero
      
      Free me
      

      // Try and show it now.. Now it's all empty
      Display(me)
      

      Sync
      waitkey
      

      
      
Function Display(p as PlayerInfo Pointer)

   if int(p)
      print "Contents Of Me Type"
      print "Me.a="+str$(p.a)
      print "Me.b="+str$(p.b)
      print "Me.c="+p.c
      print ""      
   else
      print "Pointer is null"   
   endif

EndFunction
                  

[/pbcode]