How to return double [] in jni input argument

In my Java code, I have defined the following function signature:

public native boolean getData( double [] data );

      

In my C ++ code, I would like to populate the data of a double array to get back to Java, and the boolean return from the function will indicate whether the data was set correctly or not.

javah created the following C ++ function signature:

JNIEXPORT jboolean JNICALL Java_com_test_getData___3D( JNIEnv* pEnv, jclass cls, jdoubleArray dArray ) 

      

How do I implement this function in C ++ so that I can return 3 double values ​​generated in C ++ code?

I would like to do something similar to this article: http://www.javaworld.com/article/2077554/learn-java/java-tip-54--returning-data-in-reference-arguments-via-jni .html Just instead of using StringBuffer I would like to fill in the array of doubles with values.

+3


source to share


2 answers


It should look like this:

JNIEXPORT jboolean JNICALL Java_com_test_getData___3D( JNIEnv* pEnv, jclass cls, jdoubleArray dArray )
{
    jboolean isCopy1;
    jdouble* srcArrayElems = 
           pEnv->GetDoubleArrayElements(dArray, &isCopy1);
    jint n = pEnv->GetArrayLength(dArray);
    jboolean res = false;

    // here update srcArrayElems values, maybe set res to true

    if (isCopy1 == JNI_TRUE) {
       pEnv->ReleaseDoubleArrayElements(dArray, srcArrayElems, JNI_ABORT);
    }
    return res ;
}

      

When you call getdata, your array should already be allocated - this means it is of the correct length.



I haven't compiled this code, you can find many samples on google, here are some good links:

http://www.ict.nsc.ru/win/docs/java/tutorial/native1.1/implementing/array.html http://statweb.stanford.edu/~naras/java/course/lec5/lec5. html

+4


source


Instead of returning a boolean value, consider returning a set of doubles: {x, y, z, isValid}, where isValid == 0 means "false".

jdoubleArray Java_com_test_getData__3D(JNIEnv *env, jclass cls)
{
  double xyzValid[4];
  populateMyData(xyzValid);

  jdoubleArray jXyzValid = env->NewDoubleArray(4);
  env->SetDoubleArrayRegion(jXyzValid , 0, 4, xyzValid);

  return jXyzValid;
}

      



Another option would be to return {x, y, z} for success and NULL for failure.

0


source







All Articles