Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

JNI Example (Mac OS)

JNI (Java Native Interface) allows implementing methods in C/C++, and use them in Java.

1. Create JNIExample.java file

class JNIExample {

  // Native method, no body.
  public native void sayHello(int length);

  public static void main (String args[]) {
    String str = "Hello, world!";

    (new JNIExample()).sayHello(str.length());
  }

  // This loads the library at runtime. NOTICE: on *nix/Mac the extension of the
  // lib should exactly be `.jnilib`, not `.so`, and have `lib` prefix, i.e.
  // the library file should be `libjniexample.jnilib`.
  static {
    System.loadLibrary("jniexample");
  }
}

2. Compile the JNIExample.java file

This gives you JNIExample.class:

javac JNIExample.java

3. Codegen .h file for JNI

javah -jni JNIExample

This gives you JNIExample.h (do not edit it manually!):

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNIExample */

#ifndef _Included_JNIExample
#define _Included_JNIExample
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNIExample
 * Method:    sayHello
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_JNIExample_sayHello
  (JNIEnv *, jobject, jint);

#ifdef __cplusplus
}
#endif
#endif

4. Create JNIExample.c

Native implementation:

#include <stdio.h>
#include <jni.h>
#include "JNIExample.h"

JNIEXPORT void JNICALL Java_JNIExample_sayHello
  (JNIEnv *env, jobject object, jint len) {
  printf("\nThe length of your string is %d.\n\n", len);
}

5. Compile C library

IMPORTANT: library extension should exactly be .jnilib (not .so!), and should have lib prefix, i.e. libjniexample.jnilib:

gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/" -o libjniexample.jnilib -shared JNIExample.c

NOTICE: the $JAVA_HOME can be taken from (for 1.8 version in this case):

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"

6. Execute the java class

Notice, we set java.library.path to current directory, where the libjniexample.jnilib was compiled to:

java -Djava.library.path=. JNIExample

Result:

The length of your string is 13.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.