1

请原谅我,因为我是 c++ jni 环境的新手

我正在尝试通过 JNI 桥将 Java 中的 String[] 数组传递给 c++,同时遵循我在此处找到的提示,给出以下代码段:

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

我已经在我的代码中尝试了很多方法,但我仍然从 logcat 和我的应用程序停止中收到“无法修复的损坏”错误。请查看我的代码和帮助。非常感谢你。

我的代码:

JNIEXPORT void Java_ran_com_FirstActivity_Example(
        JNIEnv *javaEnvironment, jobject self, jobjectArray stringArray, jlongArray params) {
    // Convert the input jlong array to a regular int array.
    jlong *longParams = javaEnvironment->GetLongArrayElements(params, JNI_FALSE);
    int arr[6];
    for (int n = 0; n < 6; n++) arr[n] = longParams[n];
    javaEnvironment->ReleaseLongArrayElements(params, longParams, JNI_ABORT);


    int stringCount = javaEnvironment->GetArrayLength(stringArray);

    for (int i=0; i<stringCount; i++) {
        jstring string = (jstring) (javaEnvironment->GetObjectArrayElement(stringArray, 2));
        const char *rawString = javaEnvironment->GetStringUTFChars(string, 0);
        // a method I created
        example = new Example(rawString, arr);
        javaEnvironment->ReleaseStringUTFChars(string, rawString);
    }

}
4

2 回答 2

1
int stringCount = javaEnvironment->GetArrayLength(stringArray);

for (int i=0; i<stringCount; i++) {
    jstring string = (jstring) (javaEnvironment->GetObjectArrayElement(stringArray, 2));

您可能确实打算调用以下行来枚举stringArray.

    jstring string = (jstring)(javaEnvironment->GetObjectArrayElement(stringArray, i);
    //i, not 2
于 2016-11-24T16:03:18.413 回答
1

非常感谢 timrau 让我有信心深入研究我的“jni”代码。我最终通过将字符串提取为字符来解决了这个问题,然后再将它们传递给我将使用它们的方法

JNIEXPORT void Java_ran_com_FirstActivity(JNIEnv *javaEnvironment, jobject self, jobjectArray stringArray) {

    int stringCount = javaEnvironment->GetArrayLength(stringArray);

    for (int i=0; i<stringCount; i++) {
            jstring string = (jstring) (javaEnvironment->GetObjectArrayElement(stringArray, 0));
            const char *rawString = javaEnvironment->GetStringUTFChars(string, JNI_FALSE);

            jstring istring = (jstring) (javaEnvironment->GetObjectArrayElement(stringArray, 1));
            const char *rawStringb = javaEnvironment->GetStringUTFChars(istring, JNI_FALSE);
            // I extracyed both string items to different chars before passing //to my methods...since jni only support passing two custom parameters
            example = new SuperpoweredExample(rawString, rawStringb);
            javaEnvironment->ReleaseStringUTFChars(string, rawString);
            javaEnvironment->ReleaseStringUTFChars(istring, rawStringb);
        }

}
于 2016-12-07T05:43:04.343 回答