Learn Java

Another Example - Return C string to Java

The example can be found in cToJava/GetHello.c and cToJava/GetHello.h. This example uses anohter JNI function.

Recall: JNIEnv * is the pointer, we use which to call the JNI functions.

GetHello.c:

JNIEXPORT jstring JNICALL Java_GetHello_sayHi(JNIEnv *env, jobject obj)

{
    char buffer[20];
    scanf("%s", buffer);
    return (*env)->NewStringUTF(env, buffer);
}

GetHello.java

public class GetHello{

    public native String sayHi();

    static { 
        System.loadLibrary("HelloImpl"); 
    } 

    public static void main(String[] args){
        GetHello hello = new GetHello();
        System.out.println("java:  "  + hello.sayHi());
    }

}

Code of converting between jstring and char * can be found in this blog.