JNA:Java等价于C Structures,Structure包含另一个结构变量

时间:2016-09-21 15:05:50

标签: java jna

我需要帮助定义C Structures的JAVA JNA等价物,其中每个结构包含另一个结构变量

代码

 typedef struct algorithm_list {

    unsigned char num_of_alg;
    unsigned short *algorithm_guid[];

} algorithm_list_t;

typedef struct key_data {

    unsigned char *key;

    unsigned short key_length;

    algorithm_list_t *algorithms;

} key_data_t;


   typedef struct key_array {

    unsigned char read_byte;

    unsigned char number_of_keys;

    key_data_t *keys[];

} key_array_t;

我无法正确定义JAVA JNA等效的这些结构,因为我实现的内容会给我带来无效的内存访问错误。

1 个答案:

答案 0 :(得分:0)

这些都没有struct字段。请记住[]*更紧密地绑定(更高的优先级),你分别有一个指向short的指针数组,一个指向struct的指针(或指向连续的指针)数组struct,更有可能),以及一个指向struct的数组。

指针类型的最简单映射是Pointer。一旦你开始工作,你可以将它改进为更具体的类型。

struct*应使用Structure.ByReference作为字段类型,其中一组数组为Structure.ByReference[]

JNA FAQ中所述(为了简洁省略getFieldOrder()和构造函数):

public class algorithm_list extends Structure {
    public static class ByReference extends algorithm_list implements Structure.ByReference { }
    public byte num_of_alg;
    public Pointer[] algorithm_guid = new Pointer[1];
    public algorithm_list(Pointer p) {
        super(p);
        int count = (int)readField("num_of_alg") & 0xFF;
        algorithm_guid = new Pointer[count];
        super.read();
}

public class key_data extends Structure {
    public static class ByReference extends key_data implements Structure.ByReference { }
    public Pointer key;
    public short key_length;
    public algorithm_list.ByReference algorithms;
    public key_data(Pointer p) {
        super(p);
        super.read();
        // NOTE: if algorithms points to a contiguous block of struct,
        // you can use "algorithms.toArray(count)" to get that array
    }
}

public class key_array {
    public byte read_byte;
    public byte number_of_keys;
    public key_data.ByReference[] keys = new key_data.ByReference[1];
    public key_array(Pointer p) {
        super(p);
        int count = (int)readField("number_of_keys") & 0xFF;
        keys = new key_data.ByReference[count];
        super.read();
}