Reputation: 35
I am new to opencv with android. I want to get back an array of Mat objects from JNI. I have created an application that sends some Mat objects from java to JNI. I can return int,long and other types from JNI. How would i return Mat object or array of Mat objects? In this example it returns a long object
JNIEXPORT jlong JNICALL
Java_org_opencv_samples_fd_DetectionBasedTracker_nativeCreateObject
(JNIEnv *, jclass, jstring, jint);
Upvotes: 0
Views: 573
Reputation: 5371
On java side you need to define native
method like this:
public class DetectionBasedTracker {
public static native Mat[] nativeCreateObject(String name, int count);
}
Your need to take information about Mat
object from java and return new object as jobject
and return array as jobjectArray
:
JNIEXPORT jobjectArray JNICALL
Java_org_opencv_samples_fd_DetectionBasedTracker_nativeCreateObject
(JNIEnv *env, jclass cls, jstring str, jint count){
// cls argument - is DetectionBasedTracker.class
// take class info
jclass matCls = env->FindClass("your/package/Mat");
if (env->ExceptionOccurred())
return NULL;
// take constructor by signature
const char* constructorSignature = "(Ljava/lang/String;)V";
jmethodID constructor = env->GetMethodID(matCls, "<init>", constructorSignature);
if (env->ExceptionOccurred())
return NULL;
// create java objects array
jobjectArray matArray = env->NewObjectArray((jsize)count, matCls, NULL);
for(jsize i = 0; i < count; i++){
// create new object
jobject mat = env->NewObject(matCls, constructor, /* constructor args */ str);
// put object into array
env->SetObjectArrayElement(matArray , i, mat);
}
return matArray;
}
To learn more about constructorSignature
arguments look at Java VM Type Signatures tabel
Note: this is just a sample of creating Java objects via JNI. Using JNI only for creating instances of java objects - it's a bad practice.
Upvotes: 2