SoFunction
Updated on 2025-04-09

Android return Mat data type method via jni

In order to achieve efficient code during Android development, local C++ code is usually called. JNI is a mechanism provided by the Java language to communicate with c/c++. When using opencv for image processing, c/c++ code is usually called for related operations, and the processed results are returned to Java for display or other operations.

You can create a Mat in the java part to save the image processing result image, get the local address of Mat and pass it into the jni function:

// java
Mat res = new Mat();
jni_fun(());

C++ part creates a new Mat pointer to the memory area passed in by java, and copy the Mat data of the processed result image to this memory area, so that the Mat created in java becomes the result image:

//jni c++
void jni_fun(jlong Mataddr){
   Mat* res = (Mat*)MatAddr;
   Mat image = ImgProcess();
   res->create(,,());
   memcpy(res->data,,*);

If you need to pass the image in java into c++ for processing, and then return the result, the same principle is:

//java 
Mat res = new Mat();
jni_fun((),());
 
//c++
void jni_fun(jlong srcMat,jlong resMat){
    Mat* src = (Mat*)srcMat;
    Mat* res = (Mat*)srcMat;
    Mat image = ImgProcess(*src);
    ...
    ...
}

The above article on Android's return to Mat data type through jni is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.