Write your java program that will call a native method. For example, HelloWorld.java:
class HelloWorld {
public native void displayHelloWorld();
static {
System.loadLibrary("HelloWorldNative");
}
public static void main(String[] args) {
System.out.println("Class running");
new HelloWorld().displayHelloWorld();
}
}
Compile the class:
javac HelloWorld.java
Output:
HelloWorld.class
To generate the header file needed for the native method, run javah against the class file:
javah -jni HelloWorld
Output:
HelloWorld.h
Write the C code for you native method. Include the header file HelloWorld.h that was created in the previous step. For example, HelloWorldNative.c:
#include "HelloWorld.h"
JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject
obj)
{
printf("Hello world!\n");
return;
}
Compile the native method program HelloWorldNative.c as a dll, and specifying the directories to search for the java header files. For example:
c89 -c -o HelloWorldNative.o -W c,expo,dll
-DNEEDSIEEE754 -DNEEDSLONGLONG
-I$JAVA_HOME/J1.1/include -I$JAVA_HOME/J1.1/include/mvs
HelloWorldNative.c
For an explanation of -DNEEDSIEEE754 and -DNEEDSLONGLONG see jni_oe.html shipped in $JAVA_HOME/J1.1/jni_example, or JNI Programming.
Output:
HelloWorldNative.o
Link the object files into a dll. For example:
c89 -W l,dll -o libHelloWorldNative.so ...
...HelloWorldNative.o
Output:
libHelloWorldNative.so
Set the LIBPATH environment variable to point to the directory containing your dll libHelloWorldNative.so.
Run the java program:
java HelloWorld
- Could not load dll. EDC5207S Load request for DLL load module unsuccessful.
- Ensure the dll has the execute permission bit set.
- Ensure the program has been compiled as a dll.
- java.lang.UnsatisfiedLinkError: no xyz in shared library path
For an explanation of -DNEEDSIEEE754 and -DNEEDSLONGLONG see jni_oe.html shipped in $JAVA_HOME/J1.1/jni_example, or JNI Programming.
|