@@ -11,20 +11,23 @@ oldApproach: "JNI (Java Native Interface)"
1111modernApproach : " FFM (Foreign Function & Memory API)"
1212oldCode : |-
1313 public class CallCFromJava {
14- static { System.loadLibrary("hello -jni"); }
15- public static native int greet (String name );
14+ static { System.loadLibrary("strlen -jni"); }
15+ public static native long strlen (String s );
1616 public static void main(String[] args) {
17- int ret = greet ("Bambi");
18- System.out.println("Return value " + ret);
17+ long ret = strlen ("Bambi");
18+ System.out.println("Return value " + ret); // 5
1919 }
2020 }
2121
2222 // Run javac -h to generate the .h file, then write C:
23- // JNIEXPORT int JNICALL Java_CallCFromJava_greet(
23+ // #include "CallCFromJava.h"
24+ // #include <string.h>
25+ // JNIEXPORT jlong JNICALL Java_CallCFromJava_strlen(
2426 // JNIEnv *env, jclass clazz, jstring str) {
25- // const char* name = (*env)->GetStringUTFChars(env, str, NULL);
26- // printf("Hello %s\n", name);
27- // return 0;
27+ // const char* s = (*env)->GetStringUTFChars(env, str, NULL);
28+ // jlong len = (jlong) strlen(s);
29+ // (*env)->ReleaseStringUTFChars(env, str, s);
30+ // return len;
2831 // }
2932modernCode : |-
3033 void main() throws Throwable {
0 commit comments