How to compile dynamic library for a JNI application on linux?

后端 未结 3 439
后悔当初
后悔当初 2020-11-28 20:37

I\'m using Ubuntu 10.10

So that\'s what I did.

Hello.java:

class Hello {
        public native void sayHello();

           


        
3条回答
  •  孤城傲影
    2020-11-28 21:13

    Finally my code works. This is hello.java

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

    You should compile it as :

    $ javac hello.java 
    

    To create .h file you should run this command:

    $ javah -jni hello
    

    This is hello.h:

    JNIEXPORT void JNICALL Java_hello_sayHello
    (JNIEnv *, jobject, jint);
    

    Here is hello.c:

    #include
    #include
    #include "hello.h" 
    
    JNIEXPORT void JNICALL Java_hello_sayHello
      (JNIEnv *env, jobject object, jint len) {
      printf ( "\nLength is %d", len ); }
    

    To compile this and to create a shared library we have to run this command :

    $ gcc -I/usr/lib/jvm/java-6-openjdk/include -o libhello.so -shared hello.c
    

    Then finally run this one :

    $ java -Djava.library.path=. hello
    

提交回复
热议问题