Page 1 of 1

SetVariableDestructionCallback()

Posted: Sat Sep 05, 2015 4:50 pm
by GPI
A possiblity to defined a callback, which is automatically called before the variable becomes invalid and the used memory is given free.
(At the moment this happend on End, EndProcedure and ProcedureReturn).

Example:

Code: Select all

Procedure Destruct(*var.Integer,value)
  ; two parameters needed, first a pointer to the variable, second the value (type Integer) given by the SetVariableDestructionCallback()-function.
  Debug "Forgot to close a handle on line "+str(value)+"!"
  If *var\i
    CloseFile(*var\i)
  EndIf
  
EndProcedure

Procedure Test()
  Define handle.i
  SetVariableDestructionCallback(handle,@Destruct(),#PB_Compiler_Line)
  ; First parameter the variable, second a pointer to the destruct, third a addition value (Type Integer) for the destruction-routine 

  handle=OpenFile(#PB_Any,"delme.txt")
  WriteStringN(handle,"nonsens")
  
EndProcedure ; <- Here the variable Handle is destruct, so the procedure Destructed() is called before.

Test()
end

Re: SetVariableDestructionCallback()

Posted: Sat Sep 05, 2015 5:31 pm
by Demivec
GPI wrote:(At the moment this happend on End, EndProcedure and ProcedureReturn)
Just to complete your list it also takes place on FreeArray(), FreeMap(), FreeList() and FreeStructure().