passing string array from java to C with JNI
I have a string array like {"myname","yourname","hisname"}
and I am trying to send this array to C with using J开发者_运维百科NI. 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?
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.
}
}
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.
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
}
Remember to use
env->GetArrayLength(stringArray);
精彩评论