Simple JNI example

Create these files:

/* Simple.h */
#include "jni.h"
JNIEXPORT void JNICALL Java_Simple_displayMessage(JNIEnv *env, jobject obj);
/* Simple.c */
#include <stdio.h>
#include "Simple.h"
JNIEXPORT void JNICALL Java_Simple_displayMessage(JNIEnv *env, jobject obj) {
  printf("Hello from JNI!\n");
}
/* Simple.java */
class Simple {
  public native void displayMessage();
  static {
    System.loadLibrary("Simple");
  }
}
/* Main.java */
public class Main {
  public static void main(String[] args) {
    System.out.println("library: " + System.getProperty("java.library.path"));
    Simple simple = new Simple();
    simple.displayMessage();
  }
}

Execute following commands:

export JAVA_HOME=/wherever_your_java_path_is/
$JAVA_HOME/bin/javac *.java
$JAVA_HOME/bin/javah -jni Simple
cc -g -shared -fpic -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux \
  Simple.c -o libSimple.so
export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH
$JAVA_HOME/bin/java Main

— MAC OS X —

cc -g -shared -fpic -I/Library/Java/Home/include Simple.c -o libSimple.dylib

If you are looking for more JNI samples, take a look here: http://jnicookbook.owsiak.org