I'm currently writing a JNI accelerator library to replace Java methods on some systems (Linux x64 and macOS).
I have a working code written in Kotlin/Java with JavaCV 3.4.2
I've created a JNI library that do the same job to avoid multiple back and forth between JVM and JNI.
Example:
Kotlin side (JVM + JavaCV) without acceleration :
override fun process(image: Mat): FeaturesDetectorResult {
val faceDetection = Dlib.faceDetection(image)
...
}
JNI accelerator part:
Kotlin
@ByVal
protected external fun Process(imagePtr: Long, lines: List<opencv_core.Rect>): opencv_core.Mat?;
// method of class overriding the native method
override fun process(image: opencv_core.Mat): FeaturesDetectorResult {
val lines = ArrayList<opencv_core.Rect>()
val rotatedMat = Process(image.address(), lines)
return FeaturesDetectorResult(rotatedMat, lines)
}
C++
JNIEXPORT jlong JNICALL Java_fr_tessi_bmd_image_accel_MserFeaturesDetectorNative_Process
(JNIEnv *env, jobject self, jlong imagePtr, jobject list) {
At the end of my C++ method, I am stuck in converting a native cv::Mat
to its java counterpart opencv_core.Mat
(no constructor with native address is present).
I've looked at the sources generated by javacpp and it seems that native objects are treated as jlong
. All my tests this way lead to a crash.
Anybody knows how to pass org.bytedeco.javacpp
objects back and forth with a homemade JNI library ?
EDIT:
I've found a partial workaround to create opencv_mat.Mat
from cv::Mat
:
//Safety checks removed for simplicity
#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))
Mat* toReturnToJava;
jclass pointerClass = env->FindClass("org/bytedeco/javacpp/Pointer");
jfieldID addressFld = env->GetFieldID(pointerClass, "address", "J");
jobject pointerObj = env->AllocObject(pointerClass);
env->SetLongField(pointerObj, addressFld, ptr_to_jlong(toReturnToJava));
The Mat
is returned to Java as a jlong
while the Java side declares the return value as opencv.Mat
.
The same type of code does not seem to work for Rect (I used the constructor Rect(x, y, w, h) instead).