I've always been interested in learning more about JNI, but I appear to be stuck just getting started. I have read through several tutorials and decided to start with a simple Hello World JNI program just to get my feet wet. Unfortunately, I can't seem to get past the UnsatisfiedLink Error while running my program. Here is the code:
Hello.java
public class Hello{ public native void sayHello(); static{ System.loadLibrary("hello"); } public static void main(String[] args){ Hello h = new Hello(); h.sayHello(); } }
I compiled the above with javac Hello.java, then ran javah Hello to create the following:
Hello.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class Hello */ #ifndef _Included_Hello #define _Included_Hello #ifdef __cplusplus extern "C" { #endif /* * Class: Hello * Method: sayHello * Signature: ()V */ JNIEXPORT void JNICALL Java_Hello_sayHello (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
I then wrote Hello.c
#include <jni.h> #include <stdio.h> #include "Hello.h" JNIEXPORT void JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj){ printf("Hello World!\n"); return; } void main(){}
I compiled this on my Ubuntu machine with the following command:
gcc -I"/usr/lib/jvm/java-6-openjdk/include" -I"/usr/lib/jvm/java-6-openjdk/include/linux" Hello.c -o libHello.so
I've also tried the above with -shared, -fPIC, and a slew of other flags trying to find the magic compilation command that gets the program to run.
When I try to run my program with
java -Djava.library.path='pwd' Hello OR java -Djava.library.path=. Hello OR Simply java Hello
I always get the following error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1681) at java.lang.Runtime.loadLibrary0(Runtime.java:840) at java.lang.System.loadLibrary(System.java:1047) at Hello.<clinit>(Hello.java:5) Could not find the main class: Hello. Program will exit.
My Google skills don't seem to be up to finding a solution that works on my system. Can anyone shed any light on what I'm doing wrong?
Thanks for spending time looking at this.