Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Array of Strings from Java to C++ JNI

Good day, I am trying to copy a Java string array to C++ array using JNI. I have tried this but does not seem to be working.

char *myarray;

JNIEXPORT void JNICALL
Java_com_Example_accessArray(JNIEnv *env, jobject obj, jobjectArray stringArrays){
      int size;
         size = env->GetArrayLength(stringArrays);
    myarray = env->GetCharArrayRegion(stringArrays, 0, size, null);

}

Does the myarray hold the same values in the Java array passed? Or how can I copy the values of the java String array passed through JNI to a C++ array, so the array in C++ holds the same vale? Thanks in advance.

like image 321
irobotxx Avatar asked Oct 25 '13 13:10

irobotxx


2 Answers

You pass an array of objects so you cannot just get chars from this array. A way would be like this:

int size = env->GetArrayLength(stringArrays);

for (int i=0; i < size; ++i) 
{
    jstring string = env->GetObjectArrayElement(stringArrays, i);
    const char* mayarray = env->GetStringUTFChars(string, 0);
    .... do some work or copy it to a c++ array of char*....
    env->ReleaseStringUTFChars(string, myarray);
    env->DeleteLocalRef(string);
}
like image 174
mkaes Avatar answered Oct 29 '22 14:10

mkaes


This is the code that I use to convert a Java string array String[] to a C++ vector<string>:

void Java_com_domain_project_activity_stringArrToStringVector(JNIEnv *env, jobject obj, jobjectArray jstringArr) {
        vector<string> stringVec;

        // Get length
        int len = env->GetArrayLength(jstringArr);

        for (int i=0; i<len; i++) {
            // Cast array element to string
            jstring jstr = (jstring) (env->GetObjectArrayElement(jstringArr, i));

            // Convert Java string to std::string
            const jsize strLen = env->GetStringUTFLength(jstr);
            const char *charBuffer = env->GetStringUTFChars(jstr, (jboolean *) 0);
            string str(charBuffer, strLen);

            // Push back string to vector
            stringVec.push_back(str);

            // Release memory
            env->ReleaseStringUTFChars(jstr, charBuffer);
            env->DeleteLocalRef(jstr);
        }
}

And on the Java side the function will look like the following:

void stringArrToStringVector(String[] jstringArr);

And finally, as a side note, to convert from a Java string list to string array (which you will pass to your JNI function), you can do the following:

List<String> strList = new ArrayList<>();
// Populate strList
String[] strArr = new String[strList.size()];
strList.toArray(strArr);
like image 40
Jaime Ivan Cervantes Avatar answered Oct 29 '22 14:10

Jaime Ivan Cervantes