JNA以結構體數組為參數進行調用:
- ////// C++
- // student 結構體定義
- typedef struct
- {
- int age;
- char name[20];
- }Student;
- // 修改java對象的屬性值
- JNAAPI bool changeObjs(Student stu[],int size)
- {
- for(int i=0;i<size;i++)
- {
- stu[i].age*=10;
- strcpy(stu[i].name,"wokettas");
- }
- return true;
- }
- /////// Java
- // JNA調用方法
- Student[] stus=new Students[2];
- Student s1=new Student();
- Student s2=new Student();
- s1.age=1;
- s1.name=Arrays.copyOf("k1".getBytes(), 20);
- s2.age=2;
- s2.name=Arrays.copyOf("k2".getBytes(),20);
- stus[0]=s1; //數組賦值
- stus[1]=s2;
- Gui.gui.changeObjs(stus, stus.length);
運行報錯:
Structure array elements must use contiguous memory (bad backing address at Structure array index 1)
結構體數組必須使用連續的內存區域, 上例s1,s2都是new出來的新對象,不可能連續; 也就是說傳統方式的初始化數組不能解決, 查詢JNA api發現里面提供了:
toArray
public Structure[] toArray(int size)
Returns a view of this structure's memory as an array of structures. Note that this Structure
must have a public, no-arg constructor. If the structure is currently using a Memory
backing, the memory will be resized to fit the entire array.
修改后的代碼:
- // 測試對象數組
- Student student=new Student();
- Student[] stus=(Student[]) student.toArray(2); //分配大小為2的結構體數組
- stus[0].age=1;
- stus[0].name=Arrays.copyOf("k1".getBytes(), 20);
- stus[1].age=2;
- stus[1].name=Arrays.copyOf("k2".getBytes(),20);
- Gui.gui.changeObjs(stus, stus.length);
http://tcspecial.iteye.com/blog/1665583 //原文地址