Step 1: Write the Java Code
public class HelloWorld {
public native void greet( );
static
{
System.loadLibrary("hello");
}
public static void main (String[ ] args) {
new HelloWorld().greet( );
}
}
-
The native keyword signals to the Java compiler
that the function is a native language function.
-- i.e. greet( ) is a Native Method.
-
The implementation for NM (i.e. greet( )) is provided in a separate
native language source file.
-
static block { } loads the shared library
named hello.
-
The library name referenced in System.loadLibrary
is mapped to a native library name in a platform dependent fashion.
e.g. "hello" to libhello.so in Solaris system,
hello.dll in Windows 95/NT.
Step 2: Compile the Java Code
Step 3: Create the JNI-style header file
-
javah utility program generates a header file (HelloWorld.h)
from a Java class file.
-
The header file provides a function prototype (signature) to use in
the implementation of the native method.
-
The naming convention for the native language function is Java_PNAME_CNAME_MNAME,
where PNAME is the package name, CNAME is the class name, and MNAME is
the name of the Java native method. The package name is omitted when
the class is in the default package.
-
The function definition adds two system default parameters to user-specified
parameters. The first parameter for every native method is a JNIEnv
interface pointer, through which the native code accesses parameters and
objects passed to it from the Java application. The jobject parameter
is a reference to the object itself.
Step 4: Implement the Native Method
// ----------------------
// filename: Hello1.c
// ----------------------
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>
JNIEXPORT
void JNICALL
Java_HelloWorld_greet
(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}
-
The NM must have the same function signature as in the
header file.
-
appropriate header files must be included.
Step 5: Create the Shared Library
gcc -G -I $JAVAHOME/include
-I $JAVAHOME/include/solaris Hello1.c -o libhello.so
-
$JAVAHOME is the JDK 1.1 directory (/afs/cs.unc.edu/pkg/JDK/1.1/sparc_solaris
on capefear)
-
tip: If you do not know what $JAVAHOME is, do 'which java'
to display the full path of Java directory. Traverse up that directory
until you find $JAVAHOME, which has subdirectories bin, include, lib, source.
Then, include the following line in your .aliases
file,
alias javal 'gcc -G -I/afs/cs.unc.edu/pkg/JDK/1.1/sparc_solaris/include
-I/afs/cs.unc.edu/pkg/JDK/1.1/sparc_solaris/include/solaris'
and you can just do
javal Hello1.c -o libhello.so
-
Win32 sytax:
-- cl -I $JAVAHOME\include -I $JAVAHOME\include\win32
-LD Hello1.c -Fehello.dll
Step 6: Run the Java Program
javac HelloWorld
-
The environment variable LD_LIBRARY_PATH must include
the directory where the shared library resides.