2 Replies Latest reply: Sep 14, 2011 7:29 PM by EJP RSS

    UnsatisfiedLinkError while calling C library from Java Programm

    886017
      Hi,
      I am trying call C function from Java code but I am getting error.


      Below is the code

      package jnitest;
      
      class HelloWorld {
      
          private native void print();
      
          public static void main(String[] args) {
              new HelloWorld().print();
          }
      
          static {
              System.loadLibrary("HelloWorld");
          }
      }
      I used following commands to compile and generate header files
      $ javac -d build src/jnitest/HelloWorld.java 
      $ javah -d build -classpath build -jni jnitest.HelloWorld
      Then jnitest_HelloWorld.h was generated and I renamed it to HelloWorld.h.
      I implemented HelloWorld.h in HelloWorld.c.
      Below is the code for both the files


      HelloWorld.h
      /* DO NOT EDIT THIS FILE - it is machine generated */
      #include <jni.h>
      /* Header for class jnitest_HelloWorld */
      
      #ifndef _Included_jnitest_HelloWorld
      #define _Included_jnitest_HelloWorld
      #ifdef __cplusplus
      extern "C" {
      #endif
      /*
       * Class:     jnitest_HelloWorld
       * Method:    print
       * Signature: ()V
       */
      JNIEXPORT void JNICALL Java_jnitest_HelloWorld_print
        (JNIEnv *, jobject);
      
      #ifdef __cplusplus
      }
      #endif
      #endif
      HelloWorld.c
      #include <jni.h>
      #include <stdio.h>
      #include "HelloWorld.h"
      
      JNIEXPORT void JNICALL
      Java_HelloWorld_print(JNIEnv *env, jobject obj)
      {
        printf("Hello World!\n");
        return;
      }
      I used following commands to generate so file
      gcc -m32 -fPIC -D_REENTRANT -I/opt/jdk1.6.0_19/include -I/opt/jdk1.6.0_19/include/linux -c HelloWorld.c
      gcc -m32 -shared HelloWorld.o -o libHelloWorld.so
      after all the execution I get following directory struct in build directory
      $ ls -R
      .:
      HelloWorld.c  HelloWorld.h  jnitest  libHelloWorld.so
      
      ./jnitest:
      HelloWorld.class
      I am executing following command to run the program.
      build$ java -D. jnitest.HelloWorld
      but I am getting exception
      Exception in thread "main" java.lang.UnsatisfiedLinkError: jnitest.HelloWorld.print()V
           at jnitest.HelloWorld.print(Native Method)
           at jnitest.HelloWorld.main(HelloWorld.java:16)
      I pointed LD_LIBRARY_PATH to build directory and executed
      java -classpath build jnitest.HelloWorld
      but I am still getting the same error.
      Please help to fix the issue.

      Thanks,