35

I have a string array like {"myname","yourname","hisname"} and I am trying to send this array to C with using JNI. I could not find any clear solution for this. I have tried to take this string as a chararray but no success.

Is there a way to do this?

4 Answers 4

88

You can write a simple function that takes a jobjectArray object, cast each one to jstring and then call GetStringUTFChars on it.

Like this:

void MyJNIFunction(JNIEnv *env, jobject object, jobjectArray stringArray) { int stringCount = env->GetArrayLength(stringArray); for (int i=0; i<stringCount; i++) { jstring string = (jstring) (env->GetObjectArrayElement(stringArray, i)); const char *rawString = env->GetStringUTFChars(string, 0); // Don't forget to call `ReleaseStringUTFChars` when you're done. } } 
Sign up to request clarification or add additional context in comments.

2 Comments

is the jobject object input required?
Do I need to call DeleteLocalRef on the temporary jstring object returned by GetObjectArrayElement?
10

Yes, there is a way. You would pass the String[] into your native method from the Java side and that would come across to the C/C++ side as a jobjectArray. You would then use GetObjectArrayElement() to get a jstring at a given index and then use GetStringUTFChars() or GetStringChars() to get a C/C++ pointer to the underlying string data.

And if you don't know about it, the JNI Book is a valuable reference.

2 Comments

thx for reference. I read it. I solved my problem with sending string to C side. I tried sending array for practice and have success. Thx for help. There are two correct answers and if you don't mind, I wanna give rep to 8ball ...
The link to "JNI Book" is broken.
0

it can be done in following way:

(JNIEnv *env, jobject object, jobjectArray prdctini) { const char *param[20]; jsize stringCount = (*env).GetArrayLength(prdctini); for (int i=0; i<stringCount; i++) { jstring string = (jstring) (*env).GetObjectArrayElement( prdctini, i); param[i] = (*env).GetStringUTFChars( string, NULL); } cout<<"U_Id="<<param[0]<<endl; cout<<"aggregation="<<param[1]<<endl } 

1 Comment

How about ReleaseStringUTFChars ?
0

Remember to use

env->GetArrayLength(stringArray); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.