Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Step By Step


Step 3: Create the .h File

In this step, you use the javah utility program to generate a C header file (a .h file) from the HelloWorld Java class. The header file defines a structure that represents the HelloWorld class on the C side, and provides a C function definition 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. For example, on UNIX you would issue the following command to your favorite shell tool.

% javah HelloWorld
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 Class Structure

Look at the header file. Notice that it contains a struct definition for a structure named ClassHelloWorld. The members of this structure parallel the members of the corresponding Java class; that is to say, the fields in the struct correspond to instance variables in the class. But since HelloWorld doesn't have any instance variables, there is just a place holder in the structure. You can use the members of the struct to reference class instance variables from your C functions.

The Function Definition

In addition to the C structure that mimics the Java class, you will also notice a C function signature that looks like this:
extern void HelloWorld_displayHelloWorld(struct HHelloWorld *);
This is the definition for the C function that you will write in Step 5: Write the C Function that provides the implementation for the HelloWorld class's native method displayHelloWorld(). You must use this 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 C function that implements the native method is derived from the package name, the class name, and the name of the Java native method. Thus, the native method displayHelloWorld() within the HelloWorld class becomes HelloWorld_displayHelloWorld(). In our example, there is no package name because HelloWorld is in the default package.

You will notice that the C function accepts a single parameter even though the native method defined in the Java class accepted none. You can think of the parameter as the "this" variable in C++. Our example ignores the "this" parameter. However, the example in Arguments and Return Values describes in detail how to access the data in the "this" parameter.

See Also

javah Man Page
Developer Tools


Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Step By Step