Allocating a pointer to an array of C structs using C FFI

I'd like suggestions for improving the following function:

(define-cstruct _Slice
  ([start _intptr]
   [end _intptr]
   [stride _intptr]))

;; provide the number of dimensions and a list of triples(start end stride)
;; returns a cpointer to an array of _Slices
(define (make-slice nd range-lst)
  (define slice-ptr 
    (vector->cblock 
     (for/vector #:length nd
                 ([r (in-list range-lst)])
       (apply make-Slice r))
     _Slice))
  (set-cpointer-tag! slice-ptr 'Slice)
  slice-ptr)

The make-slice function is used to provide an argument to a C function that takes a Slice * pointer. The function accepts NULL as a valid argument. This works for my needs, but I have two questions:

1 ) Is there a better way to allocate an array of C structs on the Racket side?

_fun has forms to automatically accept vectors and convert them to cpointers but I don't think that will work for NULL pointer arguments.

Is there a better way to do this using _array? I couldn't figure out how to use arrays with C structs since make-Slice (the function created by define-cstruct) returns a pointer to a _Slice and not the data. So I can't create an array and set each element with array-set!.

2 ) Is there a way to set the cpointer tag automatically? Manually doing it here is a bit awkward, but hopefully correct.

It seems like vector->cblock could do it since it knows the type.

Ideas are appreciated! Overall the C FFI is pretty nice and I've been enjoying working with it. But it is a fairly large API and sometimes I get lost in the docs.

1 Like