user43704 user43704 - 4 months ago 27
C Question

How do I extract an array of `struct*` from a pointer to that array (in JNA)?

I need to call a function with a signature like this:

size_t findDevices(devStruct_t **devs[]);


Some example C code uses the function like this:

devStruct_t **arrOfPointers;
size_t size;
size = findDevices(&arrOfPointers);
for(size_t i = 0; i < size; i++) {
printf("devId:%d\n", arrOfPointers[i]->id);
}


How would I replicate the above code in Java using JNA?

I think the JNA function signature should look like this:

NativeLong findDevices(PointerByReference devs);


I can run this without crashing:

NativeLong size;
PointerByReference stdevs = new PointerByReference();
size = libstlink.stlink_probe_usb(stdevs);


But, I don't know how to access the structures.

Answer

You have the address of the start of the array in your "returned" pointer (stdevs.getValue()). Use that to extract the array of pointers, then initialize your structures from that.

Pointer[] ptrs = stdevs.getValue().getPointerArray(0, size.intValue());
DevStruct[] array = new DevStruct[size.intValue()];
for (int i=0;i < array.length;i++) {
    array[i] = new DevStruct(ptrs[i]);
}

public class DevStruct extends Structure {
    public DevStruct(Pointer p) {
        super(p);
        read();
    }
}