zoukankan      html  css  js  c++  java
  • JNA结构体参数传递,Java数组

    JNA以结构体数组为参数进行调用:

    Java代码  收藏代码
    1. ////// C++  
    2. // student 结构体定义  
    3. typedef struct    
    4. {  
    5.     int age;  
    6.     char name[20];  
    7. }Student;  
    8.   
    9. // 修改java对象的属性值  
    10. JNAAPI bool changeObjs(Student stu[],int size)  
    11. {  
    12.     for(int i=0;i<size;i++)  
    13.     {  
    14.         stu[i].age*=10;  
    15.         strcpy(stu[i].name,"wokettas");  
    16.     }  
    17.     return true;  
    18. }  
    19.   
    20. /////// Java  
    21. // JNA调用方法  
    22. Student[] stus=new Students[2];  
    23. Student s1=new Student();  
    24. Student s2=new Student();  
    25. s1.age=1;  
    26. s1.name=Arrays.copyOf("k1".getBytes(), 20);  
    27. s2.age=2;  
    28. s2.name=Arrays.copyOf("k2".getBytes(),20);  
    29. stus[0]=s1; //数组赋值  
    30. stus[1]=s2;  
    31. 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. 

     修改后的代码:

    Java代码  收藏代码
    1. // 测试对象数组  
    2. Student student=new Student();  
    3. Student[] stus=(Student[]) student.toArray(2); //分配大小为2的结构体数组  
    4. stus[0].age=1;  
    5. stus[0].name=Arrays.copyOf("k1".getBytes(), 20);  
    6. stus[1].age=2;  
    7. stus[1].name=Arrays.copyOf("k2".getBytes(),20);  
    8. Gui.gui.changeObjs(stus, stus.length);  

    http://tcspecial.iteye.com/blog/1665583  //原文地址

  • 相关阅读:
    POST和GET的区别
    Java设计模式6大原则
    JAVA23种工厂模式
    使用jsp实现用户登录请求
    MVC模式
    使用idea查询数据库内容
    mysql常见错误
    定义外键和建表原则
    CSS制作圆角边框
    2、JS的编写位置
  • 原文地址:https://www.cnblogs.com/shaohaixiong/p/5486511.html
Copyright © 2011-2022 走看看