| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- package space.anyi.jni.parameter;
- import java.util.Arrays;
- public class Main {
- static {
- System.load("/home/yangyi/JNI-learn/c/parameter/JNI_parameter.so");
- System.load("/home/yangyi/JNI-learn/c/parameter/JNI_object_parameter.so");
- }
- public static void main(String[] args) {
- //JNI基本数据类型的传递
- // BaseTypeTest baseTypeTest = new BaseTypeTest();
- // int sum = baseTypeTest.sum(1, 2);
- // System.out.println(sum);
- // boolean flag = baseTypeTest.booleanTypeTest(false);
- // System.out.println(flag);
- //JNI对象数据类型的传递
- ObjectTest objectTest = new ObjectTest();
- Student student = objectTest.getStudent();
- System.out.println(student);
- objectTest.printStudentInfo(student);
- System.out.println(student);
- // objectTest.free(student);
- }
- }
- class BaseTypeTest {
- //定义一个有参数和返回值的native方法
- native int sum(int val1,int val2);
- //boolean类型的测试
- native boolean booleanTypeTest(boolean flag);
- }
- class ObjectTest{
- /**
- * 通过JNI获取对象,返回的是全局的JNI引用,需要手动管理,有内存泄露的风险
- * @return
- */
- native Student getStudent();
- native void printStudentInfo(Student student);
- /**
- * 释放JNI创建的全局引用
- * @param student
- */
- native void free(Student student);
- }
- class Student{
- private String name;
- private int age;
- private float height;
- private int[] source;
- private String[] hobby;
- public Student(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public float getHeight() {
- return height;
- }
- public void setHeight(float height) {
- this.height = height;
- }
- public int[] getSource() {
- return source;
- }
- public void setSource(int[] source) {
- this.source = source;
- }
- public String[] getHobby() {
- return hobby;
- }
- public void setHobby(String[] hobby) {
- this.hobby = hobby;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void info(){
- System.out.println("My name is %s,i am %d year old,height:%f".formatted(this.name,this.age,this.height));
- }
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", age=" + age +
- ", height=" + height +
- ", source=" + Arrays.toString(source) +
- ", hobby=" + Arrays.toString(hobby) +
- '}';
- }
- }
|