1

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.

user1118764
  • 9,255
  • 18
  • 61
  • 113
  • Might be duplicated with [this](http://stackoverflow.com/questions/4181934/jni-converting-jstring-to-char) – alijandro Jan 21 '15 at 09:03

4 Answers4

2

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);
}
bonnyz
  • 13,458
  • 5
  • 46
  • 70
1

You need to convert the jstring to a native char* or string. For example:

// Get a pointer to an array of bytes representing the string in modified UTF-8 encoding
char *str = env->GetStringUTFChars(myStringArgs, NULL);

// Now you can log str

// Inform the VM that the native code no longer needs access to str
env->ReleaseStringUTFChars(myStringArg, str);

See http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html for more info on JNI functions.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • I've converted the jstring to a const char *, updated the original post with the code. When I LOGD on the const char *, nothing comes out, it seems to be a null string. – user1118764 Jan 21 '15 at 09:04
  • What does `GetStringUTFLength` return for your `jstring`? – Michael Jan 21 '15 at 09:22
-1

you can try like this,

LOGD("String from java is %s\n",charString);

it is working for me.

vkumar
  • 169
  • 3
-1

try this: __android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "text:%s ", charString );

Niedved
  • 823
  • 1
  • 7
  • 13