[racket-dev] Reading and writing binary data

From: Tobias Hammer (tobias.hammer at dlr.de)
Date: Fri May 11 04:52:15 EDT 2012


after reading this thread on make-sized-byte-string to convert an arbitrary
cpointer very efficiently into a byte string
i came up with the idea to use it for writing structured binary data to a

(define-cstruct _S ([a _int]))
(define s (make-S 3210))

(with-output-to-file "test.bin" #:mode 'binary #:exists 'replace
   (lambda ()
     (display (make-sized-byte-string s (ctype-sizeof _S)))))

Like this you can write large chunks of binary data very fast.
Where i am struggling is how to read it in again. My current approach
reads it in as a byte string and copies every byte into the c-struct.
Not very efficient and not very elegant:

(define bs (with-input-from-file "test.bin" #:mode 'binary
              (lambda () (port->bytes))))
(define ptr (malloc _S))
(for ([i (bytes-length bs)])
   (ptr-set! ptr _byte i (bytes-ref bs i)))
(define new-s (ptr-ref ptr _S))

(printf "~a\n" (S-a new-s))

It would be really useful to convert a byte string directly into a  
Like this it could be easily casted into every ctype. The above sample
could then be written as:

(define bs (with-input-from-file "test.bin" #:mode 'binary
              (lambda () (port->bytes))))
(define new-s (ptr-ref (bytes-pointer f-bs) _S))

Would this functionality be a useful addition or is there a better way to  
the same?


Tobias Hammer
DLR / Institute of Robotics and Mechatronics
Tel.: 08153/28-1487
Mail: tobias.hammer at dlr.de

Posted on the dev mailing list.