简体   繁体   English

如何从指向该数组的指针中提取“ struct *”数组(在JNA中)?

[英]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: 一些示例C代码使用如下函数:

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? 如何使用JNA在Java中复制以上代码?

I think the JNA function signature should look like this: 我认为JNA函数签名应如下所示:

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. 但是,我不知道如何访问结构。

function definition, as you can see in source code is 您可以在源代码中看到的函数定义是

size_t stlink_probe_usb(stlink_t **stdevs[]);

That type is defined into this source code 该类型已在此源代码中定义

struct _stlink {
    struct _stlink_backend *backend;
    void *backend_data;

    // Room for the command header
    unsigned char c_buf[C_BUF_LEN];
    // Data transferred from or to device
    unsigned char q_buf[Q_BUF_LEN];
    int q_len;

    // transport layer verboseness: 0 for no debug info, 10 for lots
    int verbose;
    uint32_t core_id;
    uint32_t chip_id;
    int core_stat;

    char serial[16];
    int serial_size;

    enum stlink_flash_type flash_type;
    stm32_addr_t flash_base;
    size_t flash_size;
    size_t flash_pgsz;

    /* sram settings */
    stm32_addr_t sram_base;
    size_t sram_size;

    // bootloader
    stm32_addr_t sys_base;
    size_t sys_size;

    struct stlink_version_ version;
};

You have the address of the start of the array in your "returned" pointer ( stdevs.getValue() ). 您在“返回的”指针( 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM