Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Step By Step


Step 3: Create the .h File

In this step, you use the javah utility program to generate a header file (a .h file) from the HelloWorld Java class. The header file provides a function prototype for the implementation of the native method displayHelloWorld() defined in that class.

Run javah now on the HelloWorld class that you created in the previous steps.

By default, javah places the new .h file in the same directory as the .class file. You can tell javah to place the header files in a different directory with the -d option.

The name of the header file is the Java class name with a .h appended to the end of it. For example, the command shown above will generate a file named HelloWorld.h.

The Function Definition

Look at the header file HelloWorld.h.
#includejava example-1dot1/HelloWorld.h
Java_HelloWorld_displayHelloWorld() is the function that provides the implementation for the HelloWorld class's native method displayHelloWorld, which you will write in Step 4: Write the Native Method Implementation. You use the same function signature when you write the implementation for the native method.

If HelloWorld contained any other native methods, their function signatures would appear here as well.

The name of the native language function that implements the native method consists of the prefix Java_, the package name, the class name, and the name of the Java native method. Between each name component is an underscore "_" separator. The package name is omitted when the method is in the default package. Thus, the native method displayHelloWorld within the HelloWorld class becomes Java_HelloWorld_displayHelloWorld(). In our example, there is no package name because HelloWorld is in the default package.

You will notice that the implementation of the native language function accepts two parameters even though, in its definition in the Java class, it accepts no parameters. The first parameter for every native method is a JNIEnv interface pointer. It is through this pointer that your native code accesses parameters and objects passed to it from the Java application. The jobject parameter is a reference to the object itself. For a non-static native method, such as the displayHelloWorld method in our example, this argument is a reference to the object. For static native methods, this argument would be a reference to the method's Java class. In a sense, you can think of the jobject parameter as the "this" variable in C++. Our example ignores both parameters. The next lesson, Java Native Interface Programming(in the Using the JNI to Integrate Native Code and Java Programs trail) , describes how to access the data using the JNI interface pointer env parameter.


Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Step By Step