Home > database >  How do you pass an array of structs to a C API?
How do you pass an array of structs to a C API?

Time:11-13

I have a C API which looks like this:

typedef struct Datapoints {
  double *ptr;
  uintptr_t len;
} Datapoints;

double my_function(const struct Datapoints *baseline_data,
                     uint32_t baseline_data_len,
                     const struct Datapoints *new_data);

and I'm finding it difficult to call this from Swift. The first argument is an array of pointers to Datapoints structs and the third arg is a single Datapoints struct.

This is what I've come up with, but it won't work for several reasons, the main one being that I'm trying to store up a list of unsafe pointers to later pass them in to my_function. I've obfuscated the code a bit by renaming variables and types, so please forgive me if it doesn't compile. The code basically looks like this:

var baseline_datapoints = [Datapoints]()
var current_datapoints:Datapoints = Datapoints()

// This loop was intended to build up an array `baseline_Datapoints` containing pointers to struct `Datapoints`
for reading in baseline {
    let datapoints:[Double] = reading.datapoints

    // Won't work: The pointer passed as an argument to `body` is valid only during the
    // execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or return
    // the pointer for later use.
    // We _are_ attempting to store it for later use.            
  • Related