Start of Tutorial > Start of Trail |
Search
Feedback Form |
This lesson walks you through the steps necessary to integrate native code with programs written in Java.This lesson implements the canonical "Hello World!" program. The "Hello World!" program has one Java class, called
HelloWorld
.HelloWorld.java
does two things: it declares a native method that displays "Hello World!" and it implements themain
method for the overall program. The implementation for the native method is provided in C.
Note : This lesson assumes that you are starting with neither existing C functions nor Java classes. While "in the real world" you probably have existing C functions that you wish to integrate with Java programs, you will still need to modify the signatures for these C functions to work with the JNI. To be sure that you use the correct signatures, it is best to begin by writing and compiling the Java code, as described here.
Writing native methods for Java programs is a multi-step process.
main
method which calls the native method.main
method. javah
with the native interface flag -jni
. Once you've generated the header file you have the formal signature for
your native method.The following figure illustrates these steps for the Hello World program:
Create a Java class namedHelloWorld
that declares a native method. This class also includes amain
method that creates aHelloWorld
object and calls the native method.
Use javac
to compile the Java code that you wrote in Step 1.
Usejavah
to create a JNI-style header file (a.h
file) from theHelloWorld
class. The header file provides a function signature for the implementation of the native methoddisplayHelloWorld
.
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 class.
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).
And finally, use java
, the Java interpreter, to run the program.
Start of Tutorial > Start of Trail |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.