Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
masay Avatar asked May 12 '11 00:05

masay


2 Answers

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.
    }
}
like image 165
8ball Avatar answered Nov 05 '22 16:11

8ball


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.

like image 34
QuantumMechanic Avatar answered Nov 05 '22 15:11

QuantumMechanic