- Write the Java Code
The following Javacode segment defines a class named HelloWorld. This class declares one native method, implements a main method, and has a static code segment.
class HelloWorld {
public native void displayHelloWorld();
static {
System.loadLibrary(“hello”);
}
public static void main(String[] args) {
new HelloWorld().displayHelloWorld();
}
}
- Compile the Java Code
Use the Java compiler to compile the class that you created
in the previous step. Here’s the command to use:
javac HelloWorld.java
- Create the .h File
Running javah :
UNIX & LINUX
% javah -jni HelloWorld
DOS shell (Windows 95/NT)
C:\> javah -jni HelloWorld
MacOS
Drag the HelloWorld.class file onto the JavaH icon. This creates a file called HelloWorld.h in the same folder as JavaH. Move the file into your working folder. - Write the Native Method Implementation
This implementation is in the file named HelloWorldImp.c.
#include
#include “HelloWorld.h”
#include
JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
{
printf(“Hello world!\n”);
return;
}
- Create a Shared Library
UNIX
cc -G -I/usr/local/java/include -I/usr/local/java/include/solaris HelloWorldImp.c -o libhello.so
LINUX
cc -shared -I/usr/local/java/include -I/usr/local/java/include/solaris HelloWorldImp.c -o libhello.so
DOS shell (Windows 95/NT)
cl -Ic:\java\include -Ic:\java\include\win32 -LD HelloWorldImp.c -Fehello.dll
Of course, you need to specify the include path that corresponds to the setup on your own machine.
- Run the Program
Now run the Java application (the HelloWorld class) with the Java interpreter, as follows:
java HelloWorld
You should see the following output:
Hello World! - PS: Set Your Library Path
UNIX
% setenv LD_LIBRARY_PATH mylibrarypath
where mylibrarypath is the name of the directory that contains libhello.so.
DOS shell (Windows 95/NT)
On Windows 95/NT, the loadLibrary()
method searches for DLLs in the same manner as other language environments do.
In c:\autoexec.bat file:
SET INCLUDE=path to find .h files
SET LIB=path to find .lib files
MacOS
The Java runtime searches the JavaSoft Folder in the Extensions folder in the System Folder for shared libraries. Create an alias to your shared library in the JavaSoft Folder.
April 9, 2004
JNI Example
Comments Off on JNI Example
No Comments
No comments yet.
RSS feed for comments on this post.
Sorry, the comment form is closed at this time.