I have question regarding how to correctly handle association (or depedency) in JNI.
Lets assume that in your shared library you have 2 classes, NativeClass1 and NativeClass2. NativeClass1 has a method void fooNative(NativeClass2* nativeObj) which allows it to perform some operation with an object of type NativeClass2.
For each of these classes, a java class is defined to wrap the corresponding native object (JavaClass1 and JavaClass2, each one having a long private member pointing to a dynamically allocated native object of type NativeClass1and NativeClass2, respectively).
I would like JavaClass1 to also have a method public void fooJava(JavaClass2 obj) (and a corresponding native method private native void call_fooNative(long nativeObject1Ptr, long nativeObject2Ptr) which will eventually call NativeClass1::void fooNative(NativeClass2* nativeObj) after casting the pointers).
How you would get the underlying long pointer (to a NativeClass2) member from JavaClass2 in order to call void JavaClass1::call_fooNative(long nativeObject1Ptr, long nativeObject2Ptr) ( assuming you pass a pointer of to NativeClass1 as the first parameter)?
I thought of 2 methods:
- Creating a public getter method for the long pointer from
JavaClass2.
But everybody could have access to the actual native object, create another shared library, perform a delete ptr on the void pointer of NativeClass2 or damage the native ojbect in some other way.
- Instead of passing the pointer to the
NativeClass2object (as the second parameter fromcall_fooNative(...), pass the actual java object of typeJavaClass2and determine the pointer withgetFieldIdandgetLongField(which is permited on a private member, as stated in The Java Native Interface: Programmer's Guide and Specification By Sheng Liang, "10.9 Violating Access Control Rules".
Which one would be the correct way in terms of design and security?