Contents |
This lesson walks you through the steps necessary to integrate native code with programs written in the Java programming language.This lesson implements the canonical "Hello World!" program. The "Hello World!" program has two Java programming language classes. The first, called
Main
, implements themain()
method for the overall program. The second, calledHelloWorld
, has one method, a native method, that displays "Hello World!". The implementation for the native method is provided in the C programming language.Background
Writing native methods for Java programs is a multistep process.
- 1. Begin by writing the Java program whose
main
method calls the native method.- 2. Create a Java programming language class that declares the native method; this class contains just the declaration or signature for the native method.
- 3. Compile the Java programming language class that declares the native method.
- 4. Generate a header file for the native method using
javah
with the native interface flag-jni
. Once you've generated the header file you have the formal signature for your native method.- 5. Write the implementation of the native method in the programming language of your choice, such as C or C++.
- 6. Compile the header and implementation files into a shared library file.
- 7. Run the Java program.
The following figure illustrates these steps for the Hello World program:
Step 1: Write the Java Code
Create a Java programming language class namedHelloWorld
that declares a native method. Also, write the main program that creates aHelloWorld
object and calls the native method.Step 2: Compile the Java Code
Usejavac
to compile the Java programming language code that you wrote in Step 1.Step 3: Create the .h File
Usejavah
to create a JNI-style header file (a.h
file) from theHelloWorld
class. The header file provides a function prototype for the implementation of the native methoddisplayHelloWorld()
, which is defined in theHelloWorld
class.Step 4: Write the Native Method Implementation
Write the implementation for the native method in a native language (such as ANSI C) source file. The implementation will be a regular function that's integrated with your Java programming language class.Step 5: Create a Shared Library
Use the C compiler to compile the.h
file and the.c
file that you created in Steps 3 and 4 into a shared library. In Windows 95/NT terminology, a shared library is called a dynamically loadable library (DLL).Step 6: Run the Program
And finally, usejava
, the Java programming language interpreter, to run the program.
Contents |