Using 'Interface' for object-oriented programming in SB
Posted: Mon Nov 25, 2019 1:52 pm
Small example for using Interface with SpiderBasic:
Code: Select all
; The Interface describes the functions/methods of the object
Interface IObject
Move(x,y)
MoveF(x.f,y.f)
Destroy()
EndInterface
; The FuncPointer structure contains the addresses to the functions
Structure IObject_FuncPointer
Move.i
MoveF.i
Destroy.i
EndStructure
; The Structure contains the *vt pointer to the Interface functions, and additional object variable declarations
Structure SObject
*vt.IObject_FuncPointer
; variables:
objectName.s
EndStructure
; The object functions
Procedure __Move(*o.SObject,x,y)
Debug "IObject.Move() -> Moving to: "+Str(x)+","+Str(y)
EndProcedure
Procedure __MoveF(*o.SObject,x.f,y.f)
Debug "IObject.MoveF() -> Moving to: "+StrF(x)+","+StrF(y)
EndProcedure
Procedure __Destroy(*o.SObject)
Debug "IObject.Destroy()"
;Debug "Destroying Object: "+*o\objectName
FreeMemory(*o\vt)
FreeMemory(*o)
EndProcedure
; This function creates the object instance
Procedure.i New_Object()
Protected *o.SObject = AllocateStructure( SObject ) ;! p_o = spider_AllocateStructure(s_sobject, null);
If *o
*o\vt = AllocateMemory( SizeOf(IObject) ) ;! p_o._vt = spider_AllocateMemory(24);
If *o\vt = 0
FreeStructure(*o)
ProcedureReturn 0
EndIf
*o\vt\Move = @__Move() ;! p_o._vt._Move = f___move;
*o\vt\MoveF = @__MoveF() ;! p_o._vt._MoveF = f___movef;
*o\vt\Destroy = @__Destroy() ;! p_o._vt._Destroy = f___destroy;
*o\objectName = "IObject("+Hex(Random($7FFFFFFF))+")"
;Debug "Created Object: "+*o\objectName
EndIf
ProcedureReturn *o
EndProcedure
Object1.IObject = New_Object()
Object2.IObject = New_Object()
Object1\Move(10, 20)
Object1\Destroy()
Object2\MoveF(10.5, 20.1)
Object2\Destroy()