JNI and pointer deletion
Hello All
Some time ago I did some modifications at a JNI function and I am
facing some problems, so I need some tips hot to solve it.
My java code calls a C++ code, that calls the java code again many
times.
In the first call to C++ from java, a C++ object is created (named
"problem"), and passed to Java (casted as a jlong), in order to, in
the next call to C++, retrieve the C++ object again.
The "create" function is like that:
[code]
JNIEXPORT jlong JNICALL create
(JNIEnv *env, jobject obj_this,
jint n, jint m,
jint nele_jac, jint nele_hess,
jint index_style, jboolean call_finalize_solution, jboolean
call_intermediate_callback)
{
/* create the IpoptProblem */
Jipopt* problem=new Jipopt(env, obj_this, n, m, nele_jac, nele_hess,
index_style,
call_finalize_solution, call_intermediate_callback);
if(problem == NULL){
return 0;
}
// return our class
return (jlong)problem;
}
[\code]
The communication between them is perfect, except for one fact, the
destroy function that delete the pointer "problem"; inside C++ code
lead to JVM crash. the delete function is like that:
[code]
JNIEXPORT void JNICALL destroy
(JNIEnv *env,
jobject obj_this,
jlong pipopt){
// cast back our class
Jipopt *problem = (Jipopt *)pipopt;
if(problem!=NULL){
delete problem;
}
}
[\code]
But there is also an interesting thing: if I call the destroy
function this way, the crash does not happen:
[code]
JNIEXPORT void JNICALL destroy
(JNIEnv *env,
jobject obj_this,
jlong pipopt){
// cast back our class
Jipopt *problem = (Jipopt *)pipopt;
if(problem!=NULL){
problem = NULL;
delete problem;
}
}
[\code]
I mean, if I point the allocated pointer to NULL before its deletion,
the crash does not occur, if I just delete it (like in the first
code), the crash happens. I think that the possible source of this
problem is the fact that the java code still holds it reference to
jlong reference. Is it right? Pointing "problem" to NULL would not
lead to memory leak if I call this function many times? Is this the
right way to do this deletion? Is this deletion necessary or the JVM
"takes care" of this deletion issue?
Bye