Java and JNI example

JAVA and JNI

pre-requisite – Install Java SE Development Kit 6u14 under /usr/jdk1.6.0_14

1) Write a JAVA class [ HelloWorld.java ]

public class HelloWorld  {

static {

System.loadLibrary(“hello”);

}

public native void printHelloWorld();

}

 

2) Compile the class using javac

sudo javac HelloWorld.java

after this HelloWorld.class file should get created.

 

3) Create header file required for writing a native program

sudo javah -jni HelloWorld

 

4) Write a helloworld.c native c program.

#include “HelloWorld.h”

#include <stdio.h>

JNIEXPORT void JNICALL

Java_HelloWorld_printHelloWorld (JNIEnv *env, jobject obj) {

READ  Debugging the Linux kernel using Eclipse/CDT and Qemu

printf(“Hello Worldn”);

}

 

5) Create a shared library.

gcc -I/usr/jdk1.6.0_14/include -I/usr/jdk1.6.0_14/include/linux -shared -o libhello.so HelloWorld.c

 

6) Write a Main java class[ Main.java ], which will call native function.

public class Main {

public static void main(String[] args) {

new HelloWorld().printHelloWorld();

}

}

 

7) Compile Main.java

javac Main.java

 

8) Run the program

java Main

 

Reference’s

1) Using the JAVA Native interface’s

2) JNI Example

3) Integrating Native methods into Java

4) Imp- Introduction to JNI

5) http://java.sun.com/docs/books/jni/html/start.html

Leave a Reply

Your email address will not be published. Required fields are marked *