[gambit-list] Questions about reading from a port and u8vector

Marc Feeley feeley at iro.umontreal.ca
Sat Jun 27 00:17:14 EDT 2009

On 26-Jun-09, at 10:37 PM, Lam Luu wrote:

> Hello everyone,
> I am working on ICFP programming contest. There is something I am  
> really
> confused about.
> Supposed that I have an input port, and I want to read the next 8  
> bytes
> as an IEEE 754 double value or a 32-bit unsigned integer, is there
> anyway to do this in Gambit? I mean, they are not string with digit  
> '0'
> - '9', but actual representation of the number.
> Secondly, is there anyway to pass an u8vector to a C-lambda, as a  
> char*
> or whatever? The C Interface section of the manual only provides
> information about character string, but not u8vector. Is it possible  
> to
> pass u8vector as char*?

The code below will write and read 64 bit floats.  The IEEE 754  
representation is not guaranteed, but on most machines that is what  
you'll get.  Beware that the endianness will be determined by the  
processor's native endianness.

To pass a u8vector to a c-lambda do this:

(define foo
   (c-lambda (scheme-object)
             "char *ptr = ___CAST(char*,___BODY(___arg1));
              ___result = ptr[0] + ptr[1] + ptr[2];"))

(pp (foo (u8vector 10 20 30))) ;; prints 60

Good luck with the contest!


(define u8vector-subtype (##subtype (u8vector)))
(define f64vector-subtype (##subtype (f64vector)))

(define (write-f64 x port)
   (let ((v (f64vector x)))
     (##subtype-set! v u8vector-subtype)
     (write-subu8vector v 0 (u8vector-length v) port)))

(define (read-f64 port)
   (let ((v (f64vector 0.0)))
     (##subtype-set! v u8vector-subtype)
     (let ((n (read-subu8vector v 0 (u8vector-length v) port)))
       (if (= n (u8vector-length v))
             (##subtype-set! v f64vector-subtype)
             (f64vector-ref v 0))

   (lambda (port)
     (write-f64 -1.5 port)
     (write-f64 +inf.0 port)
     (write-f64 3.1415926 port)))

   (lambda (port)
     (let* ((a (read-f64 port))
            (b (read-f64 port))
            (c (read-f64 port))
            (d (read-f64 port)))
       (pp (list a b c d)))))

More information about the Gambit-list mailing list