Main.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package space.anyi.jni.parameter;
  2. import java.util.Arrays;
  3. public class Main {
  4. static {
  5. System.load("/home/yangyi/JNI-learn/c/parameter/JNI_parameter.so");
  6. System.load("/home/yangyi/JNI-learn/c/parameter/JNI_object_parameter.so");
  7. }
  8. public static void main(String[] args) {
  9. //JNI基本数据类型的传递
  10. // BaseTypeTest baseTypeTest = new BaseTypeTest();
  11. // int sum = baseTypeTest.sum(1, 2);
  12. // System.out.println(sum);
  13. // boolean flag = baseTypeTest.booleanTypeTest(false);
  14. // System.out.println(flag);
  15. //JNI对象数据类型的传递
  16. ObjectTest objectTest = new ObjectTest();
  17. Student student = objectTest.getStudent();
  18. System.out.println(student);
  19. objectTest.printStudentInfo(student);
  20. System.out.println(student);
  21. // objectTest.free(student);
  22. }
  23. }
  24. class BaseTypeTest {
  25. //定义一个有参数和返回值的native方法
  26. native int sum(int val1,int val2);
  27. //boolean类型的测试
  28. native boolean booleanTypeTest(boolean flag);
  29. }
  30. class ObjectTest{
  31. /**
  32. * 通过JNI获取对象,返回的是全局的JNI引用,需要手动管理,有内存泄露的风险
  33. * @return
  34. */
  35. native Student getStudent();
  36. native void printStudentInfo(Student student);
  37. /**
  38. * 释放JNI创建的全局引用
  39. * @param student
  40. */
  41. native void free(Student student);
  42. }
  43. class Student{
  44. private String name;
  45. private int age;
  46. private float height;
  47. private int[] source;
  48. private String[] hobby;
  49. public Student(String name) {
  50. this.name = name;
  51. }
  52. public int getAge() {
  53. return age;
  54. }
  55. public void setAge(int age) {
  56. this.age = age;
  57. }
  58. public float getHeight() {
  59. return height;
  60. }
  61. public void setHeight(float height) {
  62. this.height = height;
  63. }
  64. public int[] getSource() {
  65. return source;
  66. }
  67. public void setSource(int[] source) {
  68. this.source = source;
  69. }
  70. public String[] getHobby() {
  71. return hobby;
  72. }
  73. public void setHobby(String[] hobby) {
  74. this.hobby = hobby;
  75. }
  76. public String getName() {
  77. return name;
  78. }
  79. public void setName(String name) {
  80. this.name = name;
  81. }
  82. public void info(){
  83. System.out.println("My name is %s,i am %d year old,height:%f".formatted(this.name,this.age,this.height));
  84. }
  85. @Override
  86. public String toString() {
  87. return "Student{" +
  88. "name='" + name + '\'' +
  89. ", age=" + age +
  90. ", height=" + height +
  91. ", source=" + Arrays.toString(source) +
  92. ", hobby=" + Arrays.toString(hobby) +
  93. '}';
  94. }
  95. }