Can I assign value to global variables in JNI programming?

  android, c++, java, java-native-interface

I’m new to JNI and I want to figure out how to store variables in JNI.
And here’s what I do.
I create a global variable to store a string, and create one function to modify the string, another function to read the string.
But it the program turned out to crash every time I call the "setValue" function in android studio.
So is there anything to fix this? Or is there any better way to store info(variables) in JNI programming?

std::string jstring2string(JNIEnv *env, jstring jStr) {
    if (!jStr)
        return "";

    const jclass stringClass = env->GetObjectClass(jStr);
    const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
    const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, env->NewStringUTF("UTF-8"));

    size_t length = (size_t) env->GetArrayLength(stringJbytes);
    jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL);

    std::string ret = std::string((char *)pBytes, length);
    env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT);

    env->DeleteLocalRef(stringJbytes);
    env->DeleteLocalRef(stringClass);
    return ret;
}


std::string global_s = "hi";
extern "C" JNIEXPORT void JNICALL
Java_com_ljh_bazeljnitest2_Student_setValue(
        JNIEnv* env,
        jobject thiz,
        jstring s) {
    
    global_s = jstring2string(env,s);
    
    return ;
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_ljh_bazeljnitest2_Student_getValue(
        JNIEnv* env,
        jobject /* this */) {
    return env->NewStringUTF(global_s.c_str());
}

Source: Windows Questions C++

LEAVE A COMMENT