[plt-scheme] scheme_add_managed with FFI
Many thanks. With some experiment, it seems the following works:
#lang scheme
(require scheme/foreign)
(unsafe!)
(define add-managed
(get-ffi-obj "scheme_add_managed" #f
(_fun (_pointer = #f) _scheme (_fun #:keep (box null)
_scheme _pointer -> _void)
_pointer _bool -> _pointer)))
(define (make-p)
(let ((p (malloc _pointer 'raw)))
(add-managed p (lambda (p _) (free p)) #f #f)
p))
(define p1 (make-p))
(define p2 (make-p))
(ptr-ref p1 _int)
(ptr-ref p2 _int)
(collect-garbage)
But I didn't store the (lambda (p _) (free p)) or the box anywhere. Is
it really needed?
Chongkai
Matthew Flatt wrote:
> Thanks for the concrete example in PR 10538.
>
> The key feature of that example is that a single Scheme function is
> registered as a callback twice. The default handling of callbacks is
> that only the most recently generated foreign callback is retained with
> the Scheme function used as a callback. So, the second call to
> scheme_add_managed with the same function allows the foreign callback
> generated by the first call to be GCed.
>
> The simplest solution is to provides a boxed empty list for `#:keep' in
> the callback type:
>
> (_fun #:keep (box null) _scheme _pointer -> _void)
>
>
>