Search code examples
androidandroid-ndkjava-native-interface

jni converting jstring to char


I have to convert jstring to const char. I tried the following.

jint
Java_flacTest_AudioFormatConversion_convertWavToFlac( JNIEnv* env, jobject thiz, jstring *wavefile, jstring *flacfile, jstring *tempfile) {

    const char *wave_file = (*env)->GetStringUTFChars(env, wavefile, 0);
    // use your string
    (*env)->ReleaseStringUTFChars(env, wavefile, wave_file);

    const char *flac_file = (*env)->GetStringUTFChars(env, flacfile, 0);
    // use your string
    (*env)->ReleaseStringUTFChars(env, flacfile, flac_file);

    const char *temp_file = (*env)->GetStringUTFChars(env, tempfile, 0);
    // use your string
    (*env)->ReleaseStringUTFChars(env, tempfile, temp_file);


__android_log_print(ANDROID_LOG_DEBUG,"LOG_TAG","input file path %s\n", wave_file);
__android_log_print(ANDROID_LOG_DEBUG,"LOG_TAG","input file path 2%s\n", flac_file);
__android_log_print(ANDROID_LOG_DEBUG,"LOG_TAG","input file path3 %s\n", temp_file);

When I printed the values, all are having only temp_file value. I need to convert all 3 strings to const char. What am I doing wrong here?


Solution

  • The pointer returned by GetStringUTFChars() is not valid after ReleaseStringUTFChars() is called. It sounds like the implementation happens to be re-using the storage for all three -- I would guess the pointer values are all the same.

    Either use the values, or copy the strings with strdup(), before releasing them.