guile-user
[Top][All Lists]
Advanced

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

Re: foreign objects and the garbage collector


From: adriano
Subject: Re: foreign objects and the garbage collector
Date: Tue, 21 Sep 2021 16:00:52 +0200

Hi Olivier,

thank you very much for your reply

Il giorno dom, 19/09/2021 alle 14.11 -0400, Olivier Dion ha scritto:
> On Sun, 19 Sep 2021, adriano <randomlooser@riseup.net> wrote:
> > 
> > 




> > It'd be so nice to have an example
> 
> (define (with-my-resource token proc)
>   (let ((resource #f))
>     (dynamic-wind
>       (lambda ()
>         (set! resource (open-my-resource% token)))
> 
>       (proc resource)
> 
>       (lambda ()
>         (when resource
>           (close-my-resource% resource))))))
> 
> (with-my-resource "some-internal-token" (lambda ()))

Oh my, thank you for this !

This should be included in the manual !

The example that's there currently is totally indequate, in my opinion

> > 
> 
> Says you have `open_my_resource()` and `close_my_resource()` in C in
> library "libfoo.so" 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)))))

Uhmm... I see 2 versions of open-my-resource%

The only slight difference I see is in the #:arg-types

The first one has 

(list '*) 

and the second one has 

(list int)


Maybe you you got confused while editing ?

This would be my version of close-my-resource%


(define close-my-resource%
   (eval-when (eval load compile)
     (let ((this-lib (load-foreign-library "libfoo")))
       (foreign-library-function this-lib "close_my_resource"
                                 #:return-type int
                                 #:arg-types (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.

Ok

> 
> 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.
> 

Thank you again




reply via email to

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