How to access the return value of a Java method returning java.lang.String from C ++ to JNI?

I am trying to pass a string from a Java method called from C ++. I can’t find out which JNI function I must call to access the method and return the jstring value.

My code is:

C ++ Part

main() {
    jclass cls;
    jmethodID mid;
    jstring rv;

/** ... omitted code ... */

    cls = env->FindClass("ClassifierWrapper");
    mid = env->GetMethodID(cls, "getString","()Ljava/lang/String");

    rv = env->CallStatic<TYPE>Method(cls, mid, 0);
    const char *strReturn = env->GetStringUTFChars(env, rv, 0);

    env->ReleaseStringUTFChars(rv, strReturn);
}

Java code

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

Method signature (from javap -s class)

public java.lang.String getString();
  Signature: ()Ljava/lang/String;
+3
source share
4 answers

You must have

cls = env->FindClass("ClassifierWrapper"); 

Then you need to call the constructor to get a new object:

jmethodID classifierConstructor = env->GetMethodID(cls,"<init>", "()V"); 
if (classifierConstructor == NULL) {
  return NULL; /* exception thrown */
}

jobject classifierObj = env->NewObject( cls, classifierConstructor);

You get a static method (although the method name is incorrect). But you need to get the instance method since getString () is not static.

jmethodID getStringMethod = env->GetMethodID(cls, "getString", "()Ljava/lang/String"); 

Now call the method:

rv = env->CallObjectMethod(classifierObj, getStringMethod, 0); 
const char *strReturn = env->GetStringUTFChars(env, rv, 0);
+8
source

:

Java

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

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,"<init>", "()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);
+1

, ClassifierWrapper.getString() . ClassifierWrapper.

, GetMethodId GetStaticMethodId.

, (, String), CallStaticObjectMethod(). , . jstring (. http://java.sun.com/docs/books/jni/html/types.html) GetStringUTFChars GetStringUTFLength .

JNI . ( ExceptionCheck(), ). , , .

( ), . , FindClass , GetMethodId MethodID.

.

0

()Ljava/lang/String , JVM ;, ()Ljava/lang/String;

0

Source: https://habr.com/ru/post/1757836/


All Articles