chicken-users
[Top][All Lists]
Advanced

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

[Chicken-users] Re: FFI to libgmp questions


From: Peter Keller
Subject: [Chicken-users] Re: FFI to libgmp questions
Date: Fri, 28 Jun 2002 12:40:36 -0500
User-agent: Mutt/1.2i

Hello,

On Fri, Jun 28, 2002 at 12:38:55PM +0200, felix wrote:
> If the returned string is allocated in static memory, then everything
> will work fine. But if the string is dynamically allocated, then
> you will still work with a copy of it, but the dynamically allocated
> storage (allocated by `mpz_get_str()') will be lost.
> 
> A solution would be to use a `c-pointer' return type and convert it
> to a string by hand (by copying it). Then you can free the storage
> right away.
> 
> (Sorry I don't have the MP docs at hand, so I probably misunderstand
> the semantics of `mpz_get_str()').

> char* mpz_get_str(char *space, int base, mpz_t var);

The way the above works is like this:

If space is a valid pointer to a char* array, it is filled with the
string representation of the var variable as it pertains to the base
you'd like it in. If there is not enough room in space, you will overflow.

If space is NULL, then a newly allocated char* array is constructed with the
string inside it, and returned.

Now, I understand the concept of what you have said, grab the raw return
value as a pointer, hand copy it to a string large enough to contain it,
and then manually free the original string and returnd the new garbage
collected string.

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.

Thanks for the help. It is much appreciated.

-pete




reply via email to

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