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 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?


Solution 1:

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.
    }
}

Solution 2:

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.