Native methods
Java’s motto is “write
Once, Run Anywhere.” In order to accomplish this, Java is designed to provide
all we need to write a platform-independent program. However, there may be a
time when we need to access a platform-dependent function or method. These
platform-dependent functions or methods are written in a non-java language
(typically C or C++) and are referred to as native methods. Reasons for using
native methods include interfacing with a legacy application and accessing
capabilities that are not present in the Java API.
The java Native Interface (JNI) provides the capability to access native methods through shared dynamic link libraries (DLL).
1.Create a java class for the native method and include code to load the native method’s shared library.
2. Use javah to create C language header files for the native method
3. Implement the native method as a C function library
4. Compile and link the C code to create the shared library.
An example: Fibonacci
Class NativeApp{
Public static void main(String[] args){
If(args.length ! = 1){
System.out.println(“Usage: java
NativeApp n”);
System.exit(0);
}
int n = new
Integer(args[0].intValue;
int answer = new
Native().fibonacci(n);
System.out.println(answer);
}
}
Class Native{
Public native int fibonacci(int n);
Static {
System.loadLibrary(“native”);
}
}
Using javah
Ø javah –jni Native
Ø a header file would be generated called the Native.h
3. Implementing Native Method (NativeImp.c file)
#include
<jni.h>
#include
“Navigate.h”
int fibo(int n){
if(n<=1) return 0;
if (n = =2) return
1;
return fibo(n-1) +
fibo(n-2);
}
JNIEXPORT jint
JNICALL
Java_Native_fibobacci(JNIEnv
*env, jobject obj, jint n){
Return fibo(n);
}
All we need to do is compile NativeImp.c in such way that it produces a shared library. Using version 2.0 of Microsoft c++ compiler:
Cl -ic:\jdk1.3\include
–ic:\jdk1.3\include\win32 –ic:\msvc20\include –LD NativeImp.c
c:\msvc20\lib\*.lib –Fenative.dll
Putting it all together
Ø
java
NativeApp 22
Ø
10946