有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JNA:C结构的Java等价物,包含另一个结构变量的结构

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

代码

 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) 个答案

  1. # 1 楼答案

    这些都没有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();
    }