Programming Tutorials

Sample using loadLibrary() to call Native methods in Java

By: Charles in Java Tutorials on 2007-09-12  

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)