JNI DETECTED ERROR IN APPLICATION: use of invalid jobject

Viewed 6841
public class MyOpaqueBasedJSONDict implements IMyJSONDict {

    private final long _myNativeCPPObj;
...

public IMyJSONDict getMyJSONObj(String keyName) {
        long retVal = nativeGetJSOBObject(_myNativeCPPObj,keyName);
        return (new MyOpaqueBasedJSONDict(retVal));
    }

native implementation
NIEXPORT jlong JNICALL
Java_com_hexample_myndkapplication_MyOpaqueBasedJSONDict_nativeGetJSOBObject(JNIEnv *env,
                                                                             jobject instance,
                                                                             jlong myNativeCPPObj,
                                                                             jstring keyName_) {
    const char *keyName = env->GetStringUTFChars(keyName_, 0);

    Json::Value* nativeCppJson_ptr = reinterpret_cast<Json::Value*> (myNativeCPPObj);

    Json::Value& map = *nativeCppJson_ptr;

    Json::Value& jsonVal = map[keyName];
    env->ReleaseStringUTFChars(keyName_, keyName);
    return (jlong) &jsonVal;
}

I am not able to understand why I am getting

JNI DETECTED ERROR IN APPLICATION: use of invalid jobject 0xb4019a80 08-16 03:25:56.785 20537-20537/com.hexample.myndkapplication A/art: art/runtime/java_vm_ext.cc:410] from long com.hexample.myndkapplication.MyOpaqueBasedJSONDict.nativeGetJSOBObject

Any clue how to debug invalid memory errors in ndk. I am pretty new to Android and ndk development.

5 Answers

In my case,I used jobject in multi native thread:

javaCallBackObj = env->NewGlobalRef(jobj);

Note however that the jclass is a class reference and must be protected with a call to NewGlobalRef (see the next section). Andorid Jni doc

For me it was the incoming const char * str parameter that was not playing ball with the CallStaticVoidMethod. To fix this we have to create a new jstring and pass that back to Java instead:

// str is a const char *
jstring x = env->NewStringUTF(str);
env->CallStaticVoidMethod(jclassMainClass, methodId, x);
env->DeleteLocalRef(x);

Makes sense really since JNI bridges C++ and Java and Java will only accept a Java string (jstring) not a const char *, despite passing the latter not causing a compile time error.

In my case the problem was that I was calling the native function with the rigth arguments but wrong return type

I got the similar problem in my android app. Further I found that the String argument is the "invalid jobject" mentioned by JNI. I tried input non-empty string as argument and the error gone. I don't know why it's that. I hope that it can help you as workaround.

Related