I have a Java class that matches a C++ class. The java class is named SDClass_JNI and the C++ class is called SDClass. I pass the Java class as a jobject param to my JNI method. In that JNI method, I want to then convert that jobject passed in as a param in my JNI method to the "matching" C++ method. (e.g. SDClass_JNI -> SDCLass). How can I do this?
- Save yourself the trouble and use JavaCPP: It makes everything simple :)Samuel Audet– Samuel Audet2012-10-01 13:24:03 +00:00Commented Oct 1, 2012 at 13:24
Add a comment |
1 Answer
If I understand correctly you want an implicit conversion from java class to corresponding c++ class.
This is not possible, you should write code to handle the marshaling process.
Something like:
SNDClass toSND(JNIEnv *env, jobject obj) { SNDClass result; jclass cls = env->FindClass("com/.../SDClass_JNI"); checkException(env); //TODO release jclass object (env->DeleteLocalRef(cls);)(maybe use some sort of scoped smart pointer ) jmethodID mid = env->GetMethodID(mCls, "getField1", "()D"); checkException(env); jdouble value = env->CallDoubleMethod(obj, mid); checkException(env); result.setField1(jdouble); ..... } void checkException(JNIEnv *env) { jthrowable exc = env->ExceptionOccurred(); if (NULL == exc) { return; } //TODO decide how to handle } 3 Comments
Loren Rogers
Thanks, Marius. However then what's the point of JNI if I can't convert? I have C++ objects within my C++ code that have methods that take C++ objects as params. So I can't call those C++ methods from within my JNI code with parameters "passed in" from the JVM?
Marius
take a look at JNA (github.com/twall/jna#readme). It is a more high level library but I've only used JNI. About the purpose, we're using the c/c++ code, automating marshaling is to complex for the general case.
Samuel Audet
@Marius JavaCPP doesn't do any marshalling and it works just fine! It's a bit hakish, but the point was to show that it is possible...