Access JNI Object to Java layer as reference pointer

前端 未结 2 1226
说谎
说谎 2021-01-13 21:08

I\'m writing an application where I have lot to do with JNI call and every-time I have to perform getter() call to access variable values. Instead

2条回答
  •  孤独总比滥情好
    2021-01-13 21:26

    Is it possible to access Object reference of JNI object on Java Layer?

    Yes, you can. However you cannot use it for accessing its properties. You are only able to hold its address as a long value.

    If you would like to do so, you should create your C++ objects in heap memory and return their addresses as long numbers.

    MyClass *obj = new MyClass();
    return (long) obj;
    

    In Java side you can save that address as a long number wherever you want. Since objects have been created in heap memory, they will remain valid between JNI calls.

    Also, you have to pass them to later JNI calls as a long number and then you should cast them to MyClass * in your C++ side.

    MyClass *obj = (MyClass *)thatLongNumber;
    obj->someProperty; // Access its properties and methods via -> operator
    

提交回复
热议问题