JNA struct parameter passing, Java array

Source: Internet
Author: User

JNA is called with a struct array as a parameter:

Java code
  1. C++
  2. Student definition of structural body
  3. typedef struct
  4. {
  5. int age;
  6. Char name[20];
  7. }student;
  8. Modifying the property values of a Java object
  9. JNAAPI bool Changeobjs (Student stu[],int size)
  10. {
  11. For (int i=0;i<size;i++)
  12. {
  13. stu[i].age*=10;
  14. strcpy (Stu[i].name,"Wokettas");
  15. }
  16. return true;
  17. }
  18. Java
  19. Jna Calling Method
  20. Student[] stus=new students[2];
  21. Student s1=New Student ();
  22. Student s2=New Student ();
  23. s1.age=1;
  24. s1.name=arrays.copyof ("K1". GetBytes (), 20);
  25. S2.age=2;
  26. S2.name=arrays.copyof ("K2". GetBytes (),20);
  27. stus[0]=s1; //Array assignment
  28. stus[1]=s2;
  29. Gui.gui.changeObjs (Stus, stus.length);

Operation Error:

Structure array elements must use contiguous memory (bad backing address at Structure array index 1)

The structure array must use contiguous memory regions, and the above example s1,s2 are new objects that are not contiguous; That is, the traditional way to initialize the array can not be resolved, query JNA API Discovery provides:

ToArray
ToArray (int size)

Returns A view of this structure ' s memory as an array of structures. Note that this Structure must has a public, No-arg constructor. IF The structure is currently using a Memory backing, the memory would be resized to fit the entire array.

The Modified code:

Java code
    1. Array of Test objects
    2. Student student=New Student ();
    3. Student[] stus= (student[]) Student.toarray (2); //Allocate a struct array of size 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//Original address

JNA struct parameter passing, Java array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.