Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

can't create jobject in JNI  RSS feed

 
John P. Hughes
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing Java class BigZ, an instance of which is backed by a GNU Multiple-Precision Arithmetic Library arbitrary-size integer. Some of BigZ's methods must return instances of BigZ, but I've been unable to do so. The function below, for example, causes the JVM to die.

JNIEXPORT jobject JNICALL Java_bignum_BigZ_fib2(JNIEnv* env, jobject thisObj, jlong n)
{
mpz_ptr thisNum,
thatNum;
jobject fibObj;

1thisNum = (mpz_ptr)(*env)->GetLongField(env, thisObj, valID);
2thatNum = (mpz_ptr)(*__gmp_allocate_func)(sizeof(mpz_t));
3mpz_init(thatNum);
4mpz_fib2_ui(thisNum, thatNum, n);
fibObj = (*env)->AllocObject(env, thisClass);
5(*env)->SetLongField(env, fibObj, valID, thatNum);
return fibObj;
}

I know that the GMP code on lines 1-4 works, but the JNI code that follows causes the JVM to choke. The statement on line 5 appears elsewhere in my code and works fine there. Any ideas?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not doing any error-checking at all here. Many JNI methods will register a pending exception and then return NULL on failure, so you should always check if they return 0 before proceeding. Ignoring a zero return value can easily lead to a crash on the next JNI call.

Another thing is that it looks like "thisClass" is being stored in a member variable. If that's a local reference, as returned from FindClass, then that's a big no-no. You would have to call NewGlobalRef to turn FindClass's result into a global reference before you're allowed to save it between JNI calls.
 
John P. Hughes
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thisClass is a static variable that gets initialized as part of the class initialization.

I've tried error-checking, but the code never gets that far. For example, the error-checking shown below never executes because the VM dies on the call to AllocObject.

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So is thisClass a LocalRef, or a GlobalRef?
 
John P. Hughes
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"I see," said the blind man. NewGlobalRef() and DeleteGlobalRef() were required. Thanks for the help.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!