[plt-scheme] Manipulating Scheme vectors with FFI

From: Ernie Smith (esmith at acanac.net)
Date: Sun Nov 2 19:30:58 EST 2008

Jakub Piotr Cłapa wrote:
> Ernie Smith wrote:
>> /* vector inside structure.  How to declare the same in Scheeme?  */
>> struct { int __val[ 2 ]; } ;  /* vector embedded in struct */
> This is impossible because of libffi limitations. You can workaround 
> by defining a custom type which is a struct with N fields and custom 
> access methods. See [1] for an example:
>    (define _path-type
>      (make-ctype (make-cstruct-type (build-list (/ usb-max-path-len 8)
>                                                 (lambda (i) _uint64)))
>                  #f
>                  (lambda (ptr)
>                    (let ([v (make-bytes usb-max-path-len)]
>                          [length #f])
>                     (let loop ([i 0])
>                        (let ([value (ptr-ref ptr _uint8 'abs i)])
>                          (if (or (= i usb-max-path-len) (= value 0)) 
> (set! length i)
>                              (begin
>                                (bytes-set! v i value)
>                                (loop (add1 i))))))
>                      (subbytes v 0 length)))))
Thanks for the help Jakub.

It is very disappointing to learn that vectors within structs are ill
supported by define-struct and the like.

C structs really have little to do with scheme,  but  names like
'define-cstruct'  etc does lead one to assume a capacity for
coping with a valid, commonplace declaration of a C structure.

I feel like I've been thrown back to the early days of C compilers
when some implementors just threw all the member names in a
global name space and forced you to rename all your fields prefixing
them by the struct name, then other compiler writers wrapped you on the
knuckles for exceeding name size limits.

I thought I'd never have to go back to that time.  Least of all from 
within scheme.


I'm going to hope that a kind hearted schemer out there
will take pity on me and show me a nice general way around this.

Do all the budding foreign function importers out there  really need
to be burdened with writing code fragments like the above.

Posted on the users mailing list.