Learn Java

JNI Function

You can see the example in helloJni/Hello.c:

JNIEXPORT void JNICALL Java_com_marakana_jniexamples_Hello_sayHi
(JNIEnv *env, jobject obj, jstring who, jint times) 
{
  jint i;
  jboolean iscopy;
  const char *name;
  name = (*env)->GetStringUTFChars(env, who, &iscopy);
  for (i = 0; i < times; i++) {
    printf("Hello %s\n", name);
  }
}

Notice that I use

printf("Hello %s\n", name);

instead of

printf("Hello %s\n", who);

However, primitive types can be used directly.

Because jstring obj is only the opaque references, C pointer types that refer to internal data structures in the JVM.

We must convert Java string to C string before printing it. JNIEnv * reference to JNI environment, which lets you access all the JNI fucntions.

//Convert who (Java String) into name (C string)
name = (*env)->GetStringUTFChars(env, who, &iscopy);

More detail about JNI Function can be found in SE Document.