Search code examples
javaandroidjava-native-interface

Writing jstring to logcat in JNI function


I'm trying to debug my JNI function, and in doing so I wish to display the incoming jstring argument to logcat to verify its correctness.

I've tried the following code to do so, but it keeps crashing out.

LOGD(myStringArg);

where myStringArg is declared as a jstring.

If I declare and define another jstring within my JNI function and LOGD that, it works. However, for some reason if I call LOGD on the JNI function argument it crashes. I have verified internally that the jstring is not null, and right before calling it in the Java function, I also check that the value is correct.

I've converted the jstring to a const char * as follows:

const char *charString;
charString = (const char*)(*env)->GetStringUTFChars(env, myStringArg, NULL);
LOGD(charString);

Nothing is displayed, which means charString is empty?

Any idea how to do this?

Thanks.


Solution

  • You can try to extract chars from the jstring using this method:

    const char* getCharFromString(JNIEnv* env, jstring string){
        if(string == NULL)
            return NULL;
    
        return  env->GetStringUTFChars(string ,0);
    }
    

    This way you can print your jstring as (const char*):

    LOGD(getCharFromString(env, myStringArg));
    

    If you still have problem printing this string, try to debug the content using using these methods:

    int getBytesNeededByString(JNIEnv* env, jstring string){
        return env->GetStringUTFLength(string);
    }
    
    int getNumberOfCharsInString(JNIEnv* env, jstring string){
        return env->GetStringLength(string);
    }