2

How can I write my c++ JNI function so that it returns an array of Mat to Java code? I am programming in Android environment, with the help of NDK to use also some functions of OpenCV.

My c++ function is:

 JNIEXPORT void JNICALL Java_com_micaela_myapp_MainActivity2_getFrames(JNIEnv* env, jobject object, jstring path)
{
    const char *str;
    str = env->GetStringUTFChars(path, NULL);   
    VideoCapture input_video;
    if(input_video.open(str)){
        cout<<"Video File Opened"<<endl;
    }else{
        cout<<"Video File Not Found"<<endl;
    }
    Mat image;
    Mat frameBuffer[1000];  
    int i=0;
    while(input_video.read(image)==true){
        image.copyTo(frameBuffer[i]);
        i++;
    }
}

In Java I have:

static{
    System.loadLibrary("myapp");
}
public static native void getFrames(String path);

This function now returns void and works properly. However, my purpose is to obtain the array frameBuffer from it, in order to use it in Java. How can I do this?

user140888
  • 609
  • 1
  • 11
  • 31

1 Answers1

0

One solution is to allocate an array of equal size in Java, pass it to your native getFrames() function, and inflate the Mat objects individually using your frame buffer. Please see this post for an example of passing an array to native code, and this one for a way to inflate a Java Mat from a native one.

If you really need to create the array in native code and return it, please have a look at the NewObjectArray method that's available through JNI. (Example)

Community
  • 1
  • 1
acj
  • 4,821
  • 4
  • 34
  • 49
  • It's a good idea to allocate the array of Mat in Java and pass it to getFrames(). The problem is that I know how to pass a single Mat, but I don't understand how to pass an array of these to native code. In java I have to pass a Mat[N] object, but in cpp code how can I read it? – user140888 Sep 29 '13 at 10:23
  • My apologies - the first link that I posted was wrong. I've updated my answer. The link has a good example of how to access a Java array. It doesn't pass the array to the native method directly, but instead uses `GetFieldID()` to reach across the boundary and access the Java array. – acj Sep 29 '13 at 16:29