Convert float* to jfloatArray using JNI

前端 未结 1 1498
栀梦
栀梦 2021-01-25 15:52

I obtain a float* in my c++ function and i need convert it in jfloatArray to return to my Java code.

How can i convert float* to jfloatArray?

Thanks

相关标签:
1条回答
  • 2021-01-25 16:33

    To convert float* to jfloatArray, you can use NewFloatArray,

    You can use code below:

    • Variable "data" is just simple example, so you can use your code.
    • Also, modify com_your_packagename to your real packagename.
    • You must change dot of your package name to underbar. (com.your.packagename --> com_your_packagename)

    jfloatArray Java_com_your_packagename_farrayFromJNI(JNIEnv *env, jobject thiz) {
        jfloatArray result;
        result = (*env)->NewFloatArray(env, 3);
    
        float* data;
        data = malloc(sizeof(float) * 3);
        data[0] = 123;  data[1] = 456;  data[2] = 789;
    
        (*env)->SetFloatArrayRegion(env, result, 0, 3, data);
        free(data);
    
        return result;
    }
    

    OR

    extern "C"
    {
    JNIEXPORT jfloatArray JNICALL Java_com_your_packagename_farrayFromJNI(JNIEnv *env, jobject thiz) {
    
    jfloatArray result;
        result = env->NewFloatArray(3);
    
        float* data;
        data = malloc(sizeof(float) * 3);
        data[0] = 123;  data[1] = 456;  data[2] = 789;
    
        env->SetFloatArrayRegion(result, 0, 3, data);
        free(data);
        return result;
    };
    }
    
    0 讨论(0)
提交回复
热议问题