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.
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();
}
}
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
#include "JniSample.h"
JNIEXPORT jint JNICALL Java_JniSample_sayHello (JNIEnv *env, jobject obj) {
printf("Hello World\n");
return 0;
}
$ libtool -dynamic -lSystem libJniSample.o -o libJniSample.dylib
$ export $LD_LIBRARY_PATH
In java main
Hello World
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.javaStep 3: Create the header file
$ jahah JniSampleIt 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 JniSampleIn java main
Hello World