Sunday, June 20, 2010

Log of instructions for JNI


Reference:
Edit HelloWorld.java
HelloWorld.java

class HelloWorld { private native void print(); public static void main(String[] args) { new HelloWorld().print(); } static { System.loadLibrary("HelloWorld"); } }
Compile the JAVA class -- HelloWorld.class
  $ javac HelloWorld.java
Generate the NATIVE header file -- HelloWorld.h
  $ javah -jni HelloWorld
HelloWorld.h

/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class HelloWorld */ #ifndef _Included_HelloWorld #define _Included_HelloWorld #ifdef __cplusplus extern "C" { #endif /* * Class: HelloWorld * Method: print * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
Implement the NATIVE method -- HelloWorld.c
HelloWorld.c

#include <stdio.h> #include <jni.h> #include "HelloWorld.h" JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *env, jobject obj) { printf("Hello World\n"); return; }
Compile the NATIVE source code and build the NATIVE library
  $ gcc -c -fPIC HelloWorld.c -I$JAVA_HOME/include -I$JAVA_HOME/include/linux
  $ gcc -shared HelloWorld.o -o libHelloWorld.so
Add "current" directory to the search path of share libraries
  $ export LD_LIBRARY_PATH=.
Run the HelloWorld JAVA program
  $ java HelloWorld

Hello World