I have a requirement to implement a bidirectional communication between C++ and Java where i use JNI. Most of the issues are solved by using JNI but i am worried more where i pass a pointer reference of a variable in heap memory of C++ to Java. I use the new
keyword to allocate the reference in the heap memory and pass it to Java for future references to that particular variable. So, I've to use delete
to deallocate the variable from the heap memory of C++. Usually in Java this is achieved by using overriding finalize()
method so the garbage collector invokes this method when deleting an object, but i see that finalize
is deprecated from Java 9. Is there any other way to achieve the required functionality?
C++ Code (Passing C++ Object reference to Java):
jobject Helper::toJavaHistory(const History& history) {
auto* historyPtr = new History(history);
jobject historyObject = getEnv()->NewObject(getHistoryClass(), getMethodID("History","<init>"),reinterpret_cast<jlong>(historyPtr));
return historyObject;
}
Java Code:
public class History {
public long historyPointer;
public History(long historyPointer){
this.historyPointer = historyPointer;
}
native void deleteHistory(long historyPtr);
}
JNI Native Implementation C++:
JNIEXPORT void JNICALL Java_com_example_core_History_deleteHistory
(JNIEnv * env, jobject thisHistoryObject, jlong historyPtr) {
auto* history = reinterpret_cast<History*>(historyPtr);
delete history;
}