How do I access return value of a Java method returning java.lang.String from C++ in JNI?

前端 未结 4 1306
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 15:02

I am trying to pass back a string from a Java method called from C++. I am not able to find out what JNI function should I call to access the method and be returned a jstrin

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 15:27

    The complete working solution is as below:

    Java Side

    public class ClassifierWrapper {
    public ClassifierWrapper(){}
    public String getString() { return "TEST";}
    }
    

    Native Side

    jclass cls;
    jmethodID mid;
    jstring rv;
    
    
    cls = jniEnv->FindClass("ClassifierWrapper"); //plase also consider your package name as package\name\classname
    
    jmethodID classifierConstructor = jniEnv->GetMethodID(cls,"", "()V");
    if (classifierConstructor == NULL) {
        return NULL; /* exception thrown */
    }
    jobject classifierObj = jniEnv->NewObject( cls, classifierConstructor);
    
    jmethodID getStringMethod = jniEnv->GetMethodID(cls, "getString", "()Ljava/lang/String;");
    
    rv = (jstring)(jniEnv->CallObjectMethod(classifierObj, getStringMethod));
    const char *strReturn = jniEnv->GetStringUTFChars( rv, 0);
    
    
    jniEnv->ReleaseStringUTFChars(rv, strReturn);
    

提交回复
热议问题