I'm trying to write FFI bindings to a C library that has a function that uses ***Struct as one of its parameters:
typedef struct {
char *name;
char *value;
} StructType;
extern void theFunction(StructType ***list);
which should be called, and the result used, as:
const StructType **struct_list;
theFunction(&struct_list);
for (int i = 0; struct_list[i]; i++) {
StructType *entry = struct_list[i];
printf("name: %s, value %s\n", entry->name, entry->value);
}
I can't for the life of me figure out how to create the Dart FFI bindings for this. I've tried with Pointer<Pointer<Pointer<StructType>>>
. The actual binding (the lookup().asFunction()
) seems to work, the call to the actual function seems to work, but I just can't figure out how to iterate over the ***struct_list
after the function call to get to the list of StructType
s.
Would anybody have a small example on how this can be achieved?
[EDIT] I am so close... Just having trouble accessing the individual members of the struct. Here is the method I'm currently using. Note that I'm using a struct called "Item" here, I think that makes things easier to read:
class Item extends Struct {
external Pointer<Utf8> name;
external Pointer<Utf8> value;
}
late int Function(Pointer<Pointer<Pointer<Item>>>) getItems;
typedef getItemsNative_t = Int32 Function(Pointer<Pointer<Pointer<Item>>>);
getItems = library.lookup<NativeFunction<getItemsNative_t>('get_items').asFunction();
Pointer<Pointer<Pointer<Item>>> pppItem = calloc();
getItems(pppItem);
Pointer<Pointer<Item>> ppItem = pppItem.value;
int idx = 0;
Pointer<Item> pItem = ppItem.elementAt(idx).value; // *item
while (pItem != nullptr) {
Item item = pItem.ref; // IS THIS CORRECT?
print('name = ${item.name.toDartString()}');
print('value = ${item.value.toDartString()}');
pItem = ppItem.elementAt(++idx).value;
}
calloc.free(pppItem);
This almost works. It 'gets to' every Item, except that each member access returns the value for 'name', not 'value'.
I must be doing something wrong at the line with the 'IS THIS CORRECT' comment, but I can't figure out what it is. Anybody has any idea/suggestion?