1

I have seen many examples for a JNI application. I have tried one myself and getting an exception

dileepvikram@dileepvikram-System-Product-Name:~/include$ java -Djava.Library.path=. Test
Exception in thread "main" java.lang.UnsatisfiedLinkError: no Test in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at Test.<clinit>(Test.java:9)
Could not find the main class: Test.  Program will exit.

Test.java

 public class Test {
   public native void sayHello(int length) ;
   public static void main (String args[]) {
   String str = "I am a good boy" ;
   Test h = new Test () ;
   h.sayHello (str.length() ) ;
  }
  static {
    System.loadLibrary ( "Test" ) ;
  }
 }

I have compiled he code and created a Test.h with the code

javah -jni Test

Test.c

#include "Hello.h"
#include<stdio.h>
#include "jni.h"


JNIEXPORT void JNICALL Java_hello_sayHello
  (JNIEnv *env, jobject object, jint len) {
  printf ( "\nLength is %d", len ); }
void main()
{
    printf("\nHello World\n");

}

Then I have compiled the c code with the command

gcc Test.c -o libTest.so

and then tried running the java class with the command

java -Djava.library.path=. Test

And I am getting the exception

dileepvikram@dileepvikram-System-Product-Name:~/include$ java -Djava.Library.path=. Test
Exception in thread "main" java.lang.UnsatisfiedLinkError: no Test in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at Test.<clinit>(Test.java:9)
Could not find the main class: Test.  Program will exit.

I have tried a lot ,to find the issue,any help is appreciated.

4

2 回答 2

2

First of all, your class is called Test, not hello. So your function should be:

JNIEXPORT void JNICALL Java_Test_sayHello(JNIEnv *env, jobject object, jint length)

Also, when compiling the source, use -shared and -fPIC to have gcc compile a shared object (rather than an executable):

gcc Test.c -shared -fPIC -o libTest.so

Compiling as a shared object also means that you can remove the main function from Test.c, which shouldn't be there in the first place.

于 2013-02-26T13:43:35.007 回答
0

.export LD_LIBRARY_PATH =., thus setting the library path for the current directory, the Java files to find the so.

于 2013-10-15T08:24:03.593 回答