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?

valiano
  • 16,433
  • 7
  • 64
  • 79
Loren Rogers
  • 325
  • 3
  • 13

1 Answers1

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
}
Marius
  • 833
  • 5
  • 11
  • 1
    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? – Loren Rogers Sep 27 '12 at 14:34
  • take a look at JNA (https://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 Sep 27 '12 at 15:07
  • @Marius [JavaCPP](http://code.google.com/p/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... – Samuel Audet Oct 01 '12 at 13:27