[racket] Notification when window is closed

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Sun Aug 5 17:02:10 EDT 2012

At Sun, 5 Aug 2012 12:12:24 -0500, Robby Findler wrote:
> On Sun, Aug 5, 2012 at 11:37 AM, Antonio Menezes Leitao
> <antonio.menezes.leitao at ist.utl.pt> wrote:
> > On Sun, Aug 5, 2012 at 2:27 PM, Robby Findler
> > <robby at eecs.northwestern.edu> wrote:
> >> My first guess is that the right way to do this is to use custodians
> >> to do this shutdown, not closing the window (and perhaps make closing
> >> the window shutdown the custodian, depending). Generally speaking,
> >> custodians are the abstraction that Racket uses to manage the clean
> >> shutdown of external state (like network connections, open files, open
> >> windows, etc).
> >
> > Sounds like a good idea.  Is it possible to register a finalizer in a
> > custodian?  Or something similar that allows me to call an FFI function.
> I'm not as familiar with this layer of Racket, but I think you
> probably want to start with scheme_add_managed and that region of the
> manuals.


Beware that FFI callback memory management is slightly tricky with

By default, when you pass a Racket function as a callback to a foreign
function, the callback is valid only as long as the Racket function is
reachable. Usually, it works well enough to define a function as a
module-level binding, but in the case of custodian callbacks, often a
whole namespace may go away before a custodian is shut down.

Fortunately, there's a simple solution: pass the callback function both
as both the third and fourth arguments to scheme_add_managed(). That
is, pass the function as both the callback and the callback's data.
(The data pointer supplied to scheme_add_managed() and returned to the
callback is otherwise not useful for a callback from Racket, since a
callback can be a Racket closure.)

Posted on the users mailing list.