TclOO: callback with interface class

The goal is to add an extra argument to a callback.

A callback is a proc used as a argument to another proc,

One solution is to provide an interface. A interface is a class which only provide a limit number of well-known-methods.

oo::class create interfaceIF {
  # interface-args are defined by the callback-user
  variable interface-args...
  # constructor initialise the interface-args
  constructor {args} {
    set interface-args ...
  }
  # callback-args are defined by the callback-consumer
  method callback {callback-args...} {
    # do the work using callback-args *and* interface-args
  }
}

The callback is called with a simple usage:

set myCb [interfaceIF new interface-args...]
call ... [list $myCb callback]
$myCb destroy

example

Hi, this is an "interface" class used as callback in tcl-oo

  • In the class are TWO other tcl-oo objects embedded (valBFL and colBFL)
  • the both objects are created with create *in* the namespace of the LibSq3LiteRpcServerExecIF→instance because the name was part of the variable declaration.
  • TRICK: if the instance (myInst) is deleted (destroy) than automatic the both MkBufferListC→objects are delete too because the valBFL and the colBFL are created *in* the namespace of the LibSq3LiteRpcServerExecIF→instance.
  • TRICK: no additional cleanup (destructor) is required.
oo::class create LibSq3LiteRpcServerExecIF {
  variable rpc bus tok valBFL colBFL

  constructor {myRpc myBus myTok} {
    set rpc $myRpc
    set bus $myBus
    set tok $myTok
    MkBufferListC create valBFL
    MkBufferListC create colBFL
  }

  method callback {sq3lite valL colL} {
    valBFL Reset
    valBFL AppendLA $valL
    colBFL Reset
    colBFL AppendLA $colL
    if {$bus eq "MK_NULL"} {
      $rpc Send "W" "$tok:LL" valBFL colBFL
    } else {
      $bus Reset
      $bus WriteBFL valBFL
      $bus WriteBFL colBFL
    }
  }
}

LibSq3LiteRpcServerExecIF create myInst $rpc $bus $tok
call [list myInst callback]
myInst destroy