简体   繁体   中英

Android NDK get object from Java

I want to know how to get a custom object from Java to c++?

I need to implement a method in c++ for get performance. I already have the method working in java but I want to port to c++.

On Java a I call the method like this:

private native boolean P(Mat Previous, String Name);

On CPP file I need to get the mat object. Getting string is easy! But how can I get the custom mat object similar to c++(cv::Mat)? I need to get java Mat into a cv::Mat. Here the cpp file:

JNIEXPORT bool JNICALL Java_br_raphael_detector_SimpsonDetector_P
                      (JNIEnv* env,jobject thiz, jobject Previous, jstring Name){
jboolean sim = false;

const char* N = env->GetStringUTFChars(Name,0);
std::string Nome = N;


//Release
env->ReleaseStringUTFChars(Name,N);

//Then Return
return sim;

}

A java Mat object is a totally different thing from a native cv::Mat , you can't get one directly from the other.

That said, if you know what fields are inside Mat , and you know the corresponding fields in cv::Mat , you can write a conversion function that copies the contents of the fields one-by-one.

// First get the Mat class
jclass Mat = (*env)->GetObjectClass(env, Previous);

// To get a field
jfieldId field = (*env)->GetFieldID(env, Mat, "fieldName", field type);

// To get a method
jmethodId method = (*env)->GetMethodID(env, Mat, "methodName", method signature);

from there you can read the values of fields, or call methods

// getting a field
(*env)->GetObjectField(env, Previous, field);

// calling a method
(*env)->CallObjectMethod(env, Previous, method, parameters);

refer to http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html for details

I'm one year late to the party, but the way you pass a Mat to C is with a jlong with the address of the Java's Mat. You can do something like this:

private static native boolean P(long matAddress, String name);

In C:

JNIEXPORT jboolean JNICALL Java_br_raphael_detector_SimpsonDetector_P
                  (JNIEnv* env,jobject thiz, jlong matAddress, jstring Name)
{  
    cv::Mat* image = (cv::Mat*)matAddress;
    // Do stuff with image.
}

Then you would call the method in Java like this:

P(myMat.getNativeObjAddr(), name);

OpenCV exposes this method just for cases like this. (I would link to the documentation's page but the website is not loading here, sorry.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM