0

I use ffi(-napi) to run function, in a DLL, that returns a pointer on a C structure.

const structEl = new StructType({
    label: string;
});
const structResult = StructType({
    number_of_els: ref.types.int,
    els: ref.refType(structEl);
});

I'm expecting els to be an array of structures. This question is about array of structures as a parameter but I could find no question about the returned value.

I am able to access the first element of the array, but I can't seem to access the following elements.

Am I doing anything wrong?

Pierre Arlaud
  • 4,040
  • 3
  • 28
  • 42

1 Answers1

2

It took me a little while to figure this out because the full api doc of ref is missing.

The buffer is allocated for only one structure by default (as it is a pointer), so you need to reallocate a buffer yourself, so that it not only points to the first element but goes further in the memory.

This is done using the reinterpret method:

    // const structType = new StructType({…});
    const myStructType = ref.refType(structType);
    const result = myLibraryStruct.reinterpret(n * myStructType.size); // with n being the number of elements in the array
    let el = ref.get(result, i * myStructType.size, structType); // retrieves the element in the array at rank i
Pierre Arlaud
  • 4,040
  • 3
  • 28
  • 42