Search code examples
c++java-native-interface

GetFloatArrayElements get wrong result


i have searched the solution from the internet and my code look like same with other solution. i think GetFloatArrayElements is for get array element.

here is my code:

JNIEXPORT void JNICALL
    Java_draw(JNIEnv *env, jfloatArray point){
        float temp[6];
        float x = 0;

        jfloat *body = env->GetFloatArrayElements(point, 0);

        for(int i =0; i < 6 ; i++){
            temp[i] = body[i];
            x+= body[i];
            __android_log_print(ANDROID_LOG_ERROR, "TRACKERS123", "[%f]", *(body + i) );
        }

        env->ReleaseFloatArrayElements(point, body, 0);
    }

result is always like this:

[21.774231]
[0.000000]
[21.707932]
[21.776413]
[0.000000]
[0.000000]

i have checked the calling code from debug. here is the example value:

debug


Solution

  • The signature of your Java_draw method is wrong: (source)

    • The first argument is always a JNIEnv*.
    • The second argument depends on whether the method is static or non-static:
      • If static, the second argument is a jclass.
      • If non-static, the second argument is a jobject representing the object instance.
    • The third argument is your float[].

    So the signature should be:

    JNIEXPORT void JNICALL Java_draw(JNIEnv *env, jclass klass, jfloatArray point) // static
    

    or

    JNIEXPORT void JNICALL Java_draw(JNIEnv *env, jobject obj, jfloatArray point) // non-static