[plt-scheme] Binding C-Structs Containing Fixed-Size Arrays with the FFI

From: Henk Boom (lunarc.lists at gmail.com)
Date: Mon Jan 26 15:39:10 EST 2009

2009/1/26 Jakub Piotr Cłapa <jpc-ml at zenburn.net>:
> You may want to check these threads:
> http://thread.gmane.org/gmane.lisp.scheme.plt/12987
> http://thread.gmane.org/gmane.lisp.scheme.plt/28412/focus=28509
> http://list.cs.brown.edu/pipermail/plt-scheme/2007-March/016671.html

Thank you. I've taken a look, and come up with a solution, but I'm not
sure if it's correct. Specifically, I don't know how the garbage
collector will interact with it: will the the cvector created by
make-cvector* properly "own" the buffer it references? That aside, it
seems to give the output I would expect:

#lang scheme/base
(require scheme/foreign)

(define _dReal _float)
(define _dVector3 _cvector)
(define _dVector3-direct
  (make-ctype (make-cstruct-type (list _dReal _dReal _dReal _dReal))
              (lambda (v) (cvector-ptr v))
              (lambda (s) (make-cvector* s _dReal 4))))

(define-cstruct _foo
  ((i _dVector3-direct)
   (j _dVector3-direct)))

(define s
  (make-foo (cvector _dReal 10. 20. 30. 40.)
            (cvector _dReal 11. 22. 33. 44.)))

(printf "i: ~a ~a ~a ~a~n"
        (cvector-ref (foo-i s) 0)
        (cvector-ref (foo-i s) 1)
        (cvector-ref (foo-i s) 2)
        (cvector-ref (foo-i s) 3))
(printf "j: ~a ~a ~a ~a~n"
        (cvector-ref (foo-j s) 0)
        (cvector-ref (foo-j s) 1)
        (cvector-ref (foo-j s) 2)
        (cvector-ref (foo-j s) 3))
(cvector-set! (foo-j s) 0 42.)
(printf "j: ~a ~a ~a ~a~n"
        (cvector-ref (foo-j s) 0)
        (cvector-ref (foo-j s) 1)
        (cvector-ref (foo-j s) 2)
        (cvector-ref (foo-j s) 3))

Posted on the users mailing list.