Sample using loadLibrary( ) to call Native methods in Java

By: Charles Emailed: 1731 times Printed: 2344 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Although it is rare, occasionally, you may want to call a subroutine that is written in a language other than Java. Typically, such a subroutine exists as executable code for the CPU and environment in which you are working—that is, native code. For example, you may want to call a native code subroutine to achieve faster execution time. Or, you may want to use a specialized, third-party library, such as a statistical package. However, because Java programs are compiled to bytecode, which is then interpreted (or compiled on-the-fly) by the Java run-time system, it would seem impossible to call a native code subroutine from within your Java program. Fortunately, this conclusion is false. Java provides the native keyword, which is used to declare native code methods. Once declared, these methods can be called from inside your Java program just as you call any other Java method.

To declare a native method, precede the method with the native modifier, but do not define any body for the method. For example:

public native int meth() ;

After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your Java code.

Most native methods are written in C. The mechanism used to integrate C code with a Java program is called the Java Native Interface (JNI). This methodology was created by Java 1.1 and then expanded and enhanced by Java 2. (Java 1.0 used a different approach, which is now completely outdated.) A detailed description of the JNI is beyond the scope of this book, but the following description provides sufficient information for most applications.

Note: The precise steps that you need to follow will vary between different Java environments and versions. This also depends on the language that you are using to implement the native method. The following discussion assumes a Windows 95/98/NT environment. The language used to implement the native method is C.

The easiest way to understand the process is to work through an example. To begin, enter the following short program, which uses a native method called test( ):

// A simple example that uses a native method.
public class NativeDemo {
int i;
public static void main(String args[]) {
NativeDemo ob = new NativeDemo();
ob.i = 10;
System.out.println("This is ob.i before the native method:" +
ob.i);
ob.test(); // call a native method
System.out.println("This is ob.i after the native method:" +
ob.i);
}
// declare native method
public native void test() ;
// load DLL that contains static method
static {
System.loadLibrary("NativeDemo");
}
}

Notice that the test( ) method is declared as native and has no body. This is the method that we will implement in C shortly. Also notice the static block. As explained earlier in this book, a static block is executed only once, when your program begins execution (or,more precisely, when its class is first loaded). In this case, it is used to load the dynamic link library that contains the native implementation of test( ). (You will see how to create this library soon.)

The library is loaded by the loadLibrary( ) method, which is part of the System class. This is its general form:

static void loadLibrary(String filename)

Here, filename is a string that specifies the name of the file that holds the library. For the Windows 95/98/NT environment, this file is assumed to have the .DLL extension. After you enter the program, compile it to produce NativeDemo.class. Next, you must use javah.exe to produce one file: NativeDemo.h. (javah.exe is included in the JDK.) You will include NativeDemo.h in your implementation of test( ). To produce NativeDemo.h, use the following command:

javah -jni NativeDemo

This command produces a header file called NativeDemo.h. This file must be included in the C file that implements test( ). The output produced by this command is shown here:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeDemo */
#ifndef _Included_NativeDemo
#define _Included_NativeDemo
#ifdef _ _cplusplus
extern "C" {
#endif
/*
* Class: NativeDemo
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_NativeDemo_test
(JNIEnv *, jobject);
#ifdef _ _cplusplus
}
#endif
#endif

Pay special attention to the following line, which defines the prototype for the test( ) function that you will create:

JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *, jobject);

Notice that the name of the function is Java_NativeDemo_test( ). You must use this as the name of the native function that you implement. That is, instead of creating a C function called test( ), you will create one called Java_NativeDemo_test( ). The NativeDemo component of the prefix is added because it identifies the test( ) method as being part of the NativeDemo class. Remember, another class may define its own native test( ) method that is completely different from the one declared by NativeDemo. Including the class name in the prefix provides a way to differentiate between differing
versions. As a general rule, native functions will be given a name whose prefix includes the name of the class in which they are declared.

After producing the necessary header file, you can write your implementation of test( ) and store it in a file named NativeDemo.c:

/* This file contains the C version of the
test() method.
*/
#include <jni.h>
#include "NativeDemo.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject
obj)
{
jclass cls;
jfieldID fid;
jint i;
printf("Starting the native method.\\n");
cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, cls, "i", "I");
if(fid == 0) {
printf("Could not get field id.\\n");
return;
}
i = (*env)->GetIntField(env, obj, fid);
printf("i = %d\\n", i);
(*env)->SetIntField(env, obj, fid, 2*i);
printf("Ending the native method.\\n");
}

Notice that this file includes jni.h, which contains interfacing information. This file is provided by your Java compiler. The header file NativeDemo.h was created by javah, earlier.

In this function, the GetObjectClass( ) method is used to obtain a C structure that has information about the class NativeDemo. The GetFieldID( ) method returns a C structure with information about the field named "i" for the class. GetIntField( ) retrieves the original value of that field. SetIntField( ) stores an updated value in that field. (See the file jni.h for additional methods that handle other types of data.)

After creating NativeDemo.c, you must compile it and create a DLL. To do this by using the Microsoft C/C++ compiler, use the following command line:

Cl /LD NativeDemo.c

This produces a file called NativeDemo.dll. Once this is done, you can execute the Java program, which will produce the following output:

This is ob.i before the native method: 10
Starting the native method.
i = 10
Ending the native method.
This is ob.i after the native method: 20
Note:The specifics surrounding the use of native are implementation- and environment-dependent. Furthermore, the specific manner in which you interface to Java code is subject to change. You must consult the documentation that accompanies.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

wow !!! worked well

View Tutorial          By: Rajesh at 2012-08-30 10:54:53

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Student marks calculation program in Java
Count number of vowels, consonants and digits in a String in Java
XML and Java - Parsing XML using Java Tutorial
What is Java?
FileReader and FileWriter example program in Java
Stack example in Java - push(), pop(), empty(), search()
Method Overriding in Java
arraycopy example in Java
Read from a COM port using Java program
How to use ArrayList in Java
Method Overloading (function overloading) in Java
InetAddress Example program in Java
The Basic Structure of a Simple Java program
The switch Statement example in Java
Most Emailed Articles (in Java)
The Unsigned Right Shift
Reverse a number in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to display numbers from 1 to 10 on Applet
Insert, Delete, Search, Print an int Array in Java
Steps in using verisign certificate with Glassfish appserver
Step by Step guide to setup freetts for Java
Method Overloading sample in Java
Method Override sample in Java
How Java is Organized?
Setting Up SSL on Tomcat
Compare compareTo() function of String class with Collator and CollationKey
Applet Notinited : Applet xxxxxxxxxxxx notinited
The break Statement example in Java