I'm working on a project where I have a Mat that is allocated on the heap in native code (at the request of some Java code), like so:
Mat* mat = new Mat(height, width, type, pointer_to_some_native_data_buffer);
I then create a Mat object in Java, and point it to that native Mat by using a pointer returned from native code:
Mat javaHandleToNativeMat = new Mat(pointerFromNativeCode);
After doing some processing on it from the Java side, I call a native method to free the Mat that was allocated at the beginning:
delete (Mat*) ptr;
My question is, could native memory corruption happen when the GC runs the finalizer method on the Java Mat that pointed to the native Mat?
The finalizer code is as follows:
@Override
protected void finalize() throws Throwable {
n_delete(nativeObj);
super.finalize();
}
Notice that it calls n_delete(nativeObj). I'm wondering if this could be a problem, since I previously deleted the object in native code. If it is a problem, what is the best way to fix the problem? Should I simply call release() on the native Mat, and allow it to actually be deleted in the finalizer when the GC runs?