[Top][All Lists]

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

Re: [Chicken-users] A more detailed plea for help with FFI...

From: felix winkelmann
Subject: Re: [Chicken-users] A more detailed plea for help with FFI...
Date: Wed, 15 Dec 2004 07:44:00 +0100

On Tue, 14 Dec 2004 22:54:57 -0500, Ed Watkeys <address@hidden> wrote:
> I want to create a procedure visible to Scheme code that allocates the
> struct, opens a file, and places the file pointer in fp. I want Scheme
> to assume control of the object, and call my procedure that closes the
> file associated with fp before Scheme frees the memory. Essentially, I
> want to be able to specify a destructor.
> (define whatever:make
>         (c-lambda (char-string) whatever "
>                 struct whatever w;
>                 w.fp = fopen(___arg1, \"r\");
>                 ___result_voidstar = &w;"))

[is this ok? you are returning a pointer to stack-allocated data.
But perhaps Gambit does this differently...]

> What I do not want to do is require that user Scheme code do resource
> management and remember that it created an object and now needs to
> dispose of it. I consider that Pure Evil. Is there a way to accomplish
> what I'm trying to do in Chicken?

#include <assert.h>

struct whatever {
       FILE *fp;
            /* ... */


static struct whatever *open_file(char *name)
  struct whatever *s = (struct whatever *)malloc(sizeof(struct whatever));

  s->fp = fopen(name, "r");
  assert(s->fp != NULL);
  return s;

static void close_file(struct whatever *s)

(let ([w (open_file "x2.scm")])
  (print w)
  (set-finalizer! w close_file)
  ; ...

(gc #t) ; force finalizers to be run, but will be anyway, when the program
; finishes...

(print "done.")


reply via email to

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