0

Is there a way to call a java method, which returns a String in C?
For Integer it works like that:

JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) {
jclass employeeClass = (*env)->GetObjectClass(env, employeeObject);
jmethodID midGetAge = (*env)->GetMethodID(env, employeeClass, "getAge", "()I");
int age =  (*env)->CallIntMethod(env, employeeObject, midGetAge);
return age;
}

I've searched for a long time but nothing works for String. Finally, I want to get a char*
Thanks in advance!

0

1 Answer 1

1

Below is an example of JNI code calling a method returning a string. Hope this helps.

int EXT_REF Java_JNITest_CallJava(
    JNIEnv* i_pjenv, 
    jobject i_jobject
)
{
    jclass      jcSystem;
    jmethodID   jmidGetProperty;
    LPWSTR      wszPropName = L"java.version";

    jcSystem = i_pjenv->FindClass("java/lang/System");
    if(NULL == jcSystem)
    {
        return -1;
    }
    jmidGetProperty = i_pjenv->GetStaticMethodID(jcSystem,
                      "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    if(NULL == jmidGetProperty)
    {
        return -1;
    }

    jstring joStringPropName = i_pjenv->NewString((const jchar*)wszPropName, wcslen(wszPropName));
    jstring joStringPropVal  = (jstring)i_pjenv->CallStaticObjectMethod(jcSystem, 
                               jmidGetProperty, (jstring)joStringPropName);
    const jchar* jcVal = i_pjenv->GetStringChars(joStringPropVal, JNI_FALSE);
    printf("%ws = %ws\n", wszPropName, jcVal);
    i_pjenv->ReleaseStringChars(joStringPropVal, jcVal);
    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I just have a jobject as a parameter and want to get a string of it. That can't be so difficult for String if it's so easy for int
You see, int is a primitive type returned by value - so it is easy to handle. Strings are allocated on the GC heap and they have to be properly disposed. Otherwise the memory will leak. If you remove the memory handling code from this sample, it will be not much different from the int case. Besides, if you decided to venture into the JNI area, you can't complain about the complexity.
Luckily, JNI provides a special wrapper for java.lang.String
JNI does not. At least not that I know about. However, there are several C++ libraries out there that do. For example, this one: github.com/mapbox/jni.hpp

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.