[racket-dev] FFI: pointer to an array in a C struct type

From: Neil Toronto (neil.toronto at gmail.com)
Date: Mon Dec 3 05:45:08 EST 2012

This error seems wrong:


#lang racket

(require ffi/unsafe
          ffi/unsafe/cvector)

(define-cstruct _mpz ([alloc _int]
                       [size _int]
                       [limbs (_gcable _cvector)]))

(define z (make-mpz 1 1 (list->cvector '(1) _long)))
(mpz-limbs z)

 >>> _cvector: cannot automatically convert a C pointer to a cvector


The error might be correct, though late and confusing, if a cvector's 
"base representation" isn't a pointer type. Is it?

If that error is correct, then how are FFI users meant to define a C 
struct that has a "long *" field that points to an array? I've not yet 
managed to define one whose instances survive a garbage collection cycle 
without using (_gcable _cvector). Here's one of my desperate attempts:


#lang racket

(require ffi/unsafe
          ffi/unsafe/cvector)

(define-cstruct _mpz ([alloc _int] [size _int] [limbs _gcpointer]))

(define z (make-mpz 1 1 (cvector-ptr (list->cvector '(1) _long))))

 > (ptr-ref (mpz-limbs z) _long 0)
1
 > (collect-garbage)
 > (ptr-ref (mpz-limbs z) _long 0)
139856348920568


I mean to be complain-y this time. This shouldn't be this hard to figure 
out.

Neil ⊥

Posted on the dev mailing list.