2

Hi I want to pass a character string to java from jni to java in android-ndk. suppose this is my native function.

private native int myFunc(String buffer);

This is my native function in jni:

jint Java_com_example_twolibs_myFunc(JNIEnv*  env, jobject  thiz, jstring buffString){
    //I want to pass a character array to buffString from here, that I would read from java as String.
return 0;
}

How to do it?

1
  • I don't think you can do this - reassign a new value to the object passed as parameter. I would create the new string object and return it. Commented Sep 21, 2012 at 11:16

2 Answers 2

2

I can't quite parse the question. Passing a String "to java from jni to java" sounds redundant.

If all you want is to get at the contents of the String from native code, you can use the JNI GetStringUTFChars to get a UTF-8 representation. Strings are immutable and can't be modified directly. You can create a new String from native with NewStringUTF.

Note that the string data passed to NewStringUTF must be in "modified UTF-8" form. See the JNI docs for an explanation of what that means.

If all you want to do is pass characters around, you may want to use a char[] buffer instead (GetCharArrayElements, ReleaseCharArrayElements). Note that Java language characters are UTF-16, so "jchar" is an unsigned 16-bit value (don't try to treat them as C++ 8-bit "char").

Sign up to request clarification or add additional context in comments.

2 Comments

I want to call the result = myFunc(testString) where testString will contain value passed from the jni. Note: I'm creating the testString in the Java and passing to the native function. GetStringUTFChars is used to get the value from jstring, but how to set the value to jstring buffer in the native function?
Java-language Strings are immutable. You can't rewrite them from JNI. You can use NewStringUTF to create a new string, and then return it from your JNI method (which will need to return jstring rather than jint).
1

Take a look at this , Tells you how to pass values to ndk and how to retrieve values and performing operation within ndk

http://hoodaandroid.blogspot.in/2012/07/working-with-android-ndk-native.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.