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)
{
printf("closing...\n");
fclose(s->fp);
}
<#
(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.")