[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: foreign objects and the garbage collector

From: Olivier Dion
Subject: Re: foreign objects and the garbage collector
Date: Sun, 19 Sep 2021 14:11:44 -0400

On Sun, 19 Sep 2021, adriano <> wrote:
>> If you want to avoid the problem, you should explicitely bind and
>> call the gps-close function and not rely on the garbage collector to
>> do it for you. You can use dynamic-wind to open and close
>> resources as needed.
> It'd be so nice to have an example

(define (with-my-resource token proc)
  (let ((resource #f))
      (lambda ()
        (set! resource (open-my-resource% token)))

      (proc resource)

      (lambda ()
        (when resource
          (close-my-resource% resource))))))

(with-my-resource "some-internal-token" (lambda ()))

>> That being said, make-pointer (from (system foreign-library)) is
>> probably what you are expecting. It should work with gps_close.
> Another exmple of what you mean, here, would be so nice :-)

Says you have `open_my_resource()` and `close_my_resource()` in C in
library "" where open_my_resource takes a C string and returns
an integer for the resource while close_my_resource takes the integer of
the resource:

(define open-my-resource%
  (eval-when (eval load compile)
    (let ((this-lib (load-foreign-library "libfoo")))
      (foreign-library-function this-lib "open_my_resource"
                                #:return-type int
                                #:arg-types (list '*))))

(define open-my-resource%
  (eval-when (eval load compile)
    (let ((this-lib (load-foreign-library "libfoo")))
      (foreign-library-function this-lib "open_my_resource"
                                #:return-type int
                                #:arg-types (list int)))))
Note that you probably need to do a wrapper named `open-my-resource` to
do the conversion of scm_string to C raw pointer before calling
`open-my-resource%` in this particular case.

This is just an example, but it shows you that you can call foreign C
primitives easily without any C code, and that you have to use a
dynamic context to manage the lifetime of the C resources.

Olivier Dion

reply via email to

[Prev in Thread] Current Thread [Next in Thread]