Friday, August 10, 2012

JNI : Step-by-step tutorial on OS X with GCC

Here is a simple step-by-step tutorial to write a sample JNI application on Mac OS X using gcc compiler.
Stand alone GCC  (i.e, without Xcode) can be installed from here.

Step 1: Write the java code

public class JniSample {

   public native int sayHello();

   public static void main(String[] args) {

       System.loadLibrary("JniSample");
       System.out.println("In java main");

       JniSample s = new JniSample();
       s.sayHello();
   }
}

Step 2: Compile the java code

$ javac JniSample.java

Step 3: Create the header file

$ jahah JniSample

It looks like:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JniSample */

#ifndef _Included_JniSample
#define _Included_JniSample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     JniSample
* Method:    sayHello
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_JniSample_sayHello
 (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Step 4: Write C code

#include <stdio.h>
#include "JniSample.h"

JNIEXPORT jint JNICALL Java_JniSample_sayHello (JNIEnv *env, jobject obj) {
 printf("Hello World\n");
 return 0;
}

Step 5: Compile C code and create native library

$ cc -v -c -fPIC -I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/ JniSample.c -o libJniSample.o
$ libtool -dynamic -lSystem libJniSample.o -o libJniSample.dylib

Step 6: Set LD_LIBRARY_PATH env variable:

$ LD_LIBRARY_PATH=.
$ export $LD_LIBRARY_PATH

Step 7: Run

$ java JniSample
In java main
Hello World