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
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
You want to retain a reference to a C++ object from your Java side? you can't.
Those implementations (C/Java) for representing and accessing objects/primitives are completely different. That's why there's so much mambo jambo functions when you you cast from one data type to another.