4

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?

1
  • Save yourself the trouble and use JavaCPP: It makes everything simple :) Commented Oct 1, 2012 at 13:24

1 Answer 1

2

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
@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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.