Search code examples
javaandroid-ndkjava-native-interface

How to JNI string type function mapping?


I have following table for method mapping:-

static jint sum_JNI(JNIEnv * env, jclass clazz, jint a, jint b){
    return a + b;
}

static jint mul_JNI(JNIEnv * env, jclass clazz, jint a, jint b){
    return a * b;
}

static jstring get_string(){
    return (jstring)"string";
}


static JNINativeMethod method_table[] = {
        {"sum_JNI", "(II)I", (void*) sum_JNI},
        {"mul_JNI", "(II)I", (void*) mul_JNI},
       // {"get_string","()C", (void*) get_string}
};

I don't know what is the type for jstring/string in this table. Tried above code. But it doesn't work. How to do it?


Solution

  • A jstring is a Java-language object. You can't simply cast a C string literal into one with the definitions from jni.h.

    Use the NewStringUTF function to create a jstring from a "modified" UTF-8 string literal. The object type for method declarations is Ljava/lang/String; -- there is no single-character value.

    See also JNI Tips and the interface spec.