[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: Ed Watkeys
Subject: Re: [Chicken-users] A more detailed plea for help with FFI...
Date: Wed, 15 Dec 2004 07:27:49 -0500

On Dec 15, 2004, at 1:44 AM, felix winkelmann wrote:

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

Gambit makes a bitwise copy of the returned object on the heap. The details of that are a bit cloudy right now, which is why I am again pushing ahead with my Chicken implementation.

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

I had no idea the code could be so straightforward and clean. Thank you very much.

Watkeys Product Design *
address@hidden * +1 215 694 4201

reply via email to

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