[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Chicken-users] Re: FFI to libgmp questions
From: |
Peter Keller |
Subject: |
Re: [Chicken-users] Re: FFI to libgmp questions |
Date: |
Sat, 29 Jun 2002 00:05:31 -0500 |
User-agent: |
Mutt/1.2i |
On Fri, Jun 28, 2002 at 12:40:36PM -0500, Peter Keller wrote:
> So, this is an attempt to do this:
>
> ;; convert a pointer known to be a char* into a c-string so that the
> ;; garbage collector can get it
> (define c-pointer->c-string!
> (foreign-lambda* c-string ((c-pointer ptr))
> " C_word *arena = C_alloc(C_SIZEOF_STRING(strlen(ptr) + 1));
> C_word newstr;
> newstr = C_string2(&arena, ptr);
> free(ptr); /* get rid of original memory */
> return (newstr); /* copied into gc and newstr goes away */ "))
>
> (define mpz_get_str
> (let ((alloc (foreign-lambda c-pointer "mpz_get_str" c-string int mpz_t)))
> (lambda (ptr base mpz)
> (let ((c-strptr (alloc ptr base mpz)))
> (if (equal? ptr #f)
> (c-pointer->c-string! c-strptr)
> ptr)))))
>
> Unfortunately, a call to (mpz_get_str #f 10 var) returns junk and I'm
> not sure why. I'm sure I'm missing something simple in how I'm supposed
> to do this.
Ok, here is another attempt that finally *appears* to work:
;; convert a pointer known to be a char* into a c-string so I can free the
;; c pointer later and still have a garbage collected scheme string laying
;; around.
(define c-pointer->c-string
(foreign-callback-lambda* c-string ((c-pointer ptr))
" char *arena = C_alloc(C_SIZEOF_STRING(strlen(ptr) + 1));
strcpy(arena, ptr);
return (arena); /* copied into gc-memory??? */ "))
;; if there is a return char *, then manually copy it into a c-string, and
;; free the real c-pointer returned by the function. This should make garbage
;; collection happy.
(define mpz_get_str
(let ( (alloc (foreign-lambda c-pointer "mpz_get_str" c-string int mpz_t))
(dealloc (foreign-lambda void "free" c-pointer)))
(lambda (ptr base mpz)
(let ((c-ptr (alloc ptr base mpz)))
(if (equal? ptr #f)
(let ((str (c-pointer->c-string c-ptr))) ;; copy the string...
(dealloc c-ptr) ;; remove the mem alloced by mpz_get_str
str)
ptr)))))
Does that look correct? in c-pointer->c-string, is the arena memory
going to get copied into the garbage collector correctly without leaking
any memory or using any dangling pointers?
Thanks.
-pete