我要使用的 native 函数需要一个包含 7 个 Mat
的数组:
static int nativeCode(cv::Mat &inputImg, cv::Mat bufImgs[7]);
在 jni_part
我有:
Mat& mRgba = *(Mat*)inRgba;
Mat& bufImgs[7] = *(Mat*)inBufImgs;
nativeCode(mRgba,bufImgs);
在我的 Java 代码中,我声明了我的字段:
private Mat mRgba;
private Mat[] bufImgs = new Mat[7];
我可以在 mRgba
上调用 getNativeObjAddr
,但是我该如何对数组执行等效的操作?
一些背景:
我正在使用 OpenCV,使用相机进行实时图像处理。我在每一帧上调用的函数需要一些额外的对象。为了防止每帧都创建和销毁这些对象,我想创建一次,并且每次都传递引用。
最佳答案
您必须将 Java 对象引用数组转换为 cv::Mat
的 native 数组。由于您有一个获取 native 对象地址的方法,所以这很简单。您在 Java 端创建一个 native 方法:
public class MyClass {
private Mat mRgba;
private Mat[] bufImgs = new Mat[7];
// set the fields and all...
// ...
// Call the native method
private native int callNativeCode();
}
然后在 C/C++ 端,您可以像这样实现 callNativeCode
:
JNIEXPORT jint JNICALL Java_MyClass_callNativeCode(::JNIEnv* env, jobject thisobject)
{
// Find the required classes
jclass thisclass = env->GetObjectClass(thisobject);
jclass matclass = env->FindClass("org/opencv/core/Mat");
// Get methods and fields
jmethodID getPtrMethod = env->GetMethodID(matclass, "getNativeObjAddr", "()J");
jfieldID mrgbafieldid = env->GetFieldID(thisclass, "mRgba", "Lorg/opencv/core/Mat;");
jfieldID bufimgsfieldid = env->GetFieldID(thisclass, "bufImgs", "[Lorg/opencv/core/Mat;");
// Let's start: Get the fields
jobject mrgba = env->GetObjectField(thisobject, mrgbafieldid);
jobjectArray bufimgsArray = (jobjectArray)env->GetObjectField(thisobject, bufimgsfieldid);
// Convert the array
cv::Mat nativeBufImgs[7];
for (int i = 0; i < 7; i++)
nativeBufImgs[i] = *(cv::Mat*)env->CallLongMethod(env->GetObjectArrayElement(bufimgsArray, i), getPtrMethod);
// Get the address for mRgba
cv::Mat* mrgbaptr = (cv::Mat*)env->CallLongMethod(mrgba, getPtrMethod);
// We're done! Call the method and return!
return nativeCode(mrgbaptr, nativeBufImgs);
}
关于java - 将一组垫传递给 native 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012115/