[FIXED] JNI "jobject thiz" and jboolean parameters relationship

Issue

I have a JNI code like this:

  class NativeConnector {
    public static native getKey(boolean isValid);
  }


  JNIEXPORT jstring JNICALL 
  Java_com_mg_helper_NativeConnector_getKey(JNIEnv *env, jboolean is_valid) {
      if (is_valid) {
         return (*env)->NewStringUTF(env, "48759d35c");
      } else {
         return (*env)->NewStringUTF(env, "527c4f704");
      }
   }

The problem is that is_valid in JNI is always true and result is always "48759d35c", although I send false in method getKey

   NativeConnector.getKey(false) // result is "48759d35c"

If I change JNI method with jobject, it can work well:

 JNIEXPORT jstring JNICALL 
  Java_com_mg_helper_NativeConnector_getKey(JNIEnv *env, jobject thiz , jboolean is_valid) 

According to this answer, jobject thiz is referenced to an object of type (NativeConnector), and jclass is used for static method

So the question is, what is relationship between jobject, jclass and jboolean in this case? why is jboolean paramter always true if I don’t use jobject?

Solution

The problem is that is_valid in JNI is always true

The problem is that your JNI method signature is incorrect.

why is jboolean parameter always true if I don’t use jobject?

Because not using the jobject parameter is wrong. You’re receiving the jobject argument into the jboolean parameter. The correct method signature for

class NativeConnector {
    public static native getKey(boolean isValid);
}

is

JNIEXPORT jstring JNICALL
Java_com_mg_helper_NativeConnector_getKey(JNIEnv *env, jobject *thiz, jboolean is_valid);

Whatever process you used to derive the signature Java_com_mg_helper_NativeConnector_getKey(JNIEnv *env, jboolean is_valid) should be thrown away. Use javah to generate your method signatures. It is never wrong.

Answered By – user207421

Answer Checked By – Mary Flores (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published