JNI: Library is Found on Path, but Method is not (java.lang.UnsatisfiedLinkError)

后端 未结 5 652
南笙
南笙 2021-01-12 15:43

I\'m trying to use JNI and getting java.lang.UnsatisfiedLinkError. Unlike the other million questions asked about this, I have the lib on my path, and have even seen the ex

相关标签:
5条回答
  • 2021-01-12 15:50

    Try with following example for Windows: (remember that the Java class name must be the same that corresponding file name)

    Step 1. Create the following Java file (P.java):

    class P
    {
      static
      {
        // "P" is the name of DLL without ".dll"
        System.loadLibrary ("P");
      }
    
      public static native void f(int i);
    
      public static void main(String[] args)
      {
        f(1);
      }
    }
    

    Step 2. javac P.java

    Step 3. javah P

    Then, "javah" generates the header file "P.h"

    Step 4. Create the file "P.def" including the following two lines (this file defines the exported symbols, in this case the name of C function):

    EXPORTS
    Java_P_f
    

    Step 5. Create your C file (P.c):

    #include "P.h"
    
    JNIEXPORT void JNICALL Java_P_f(JNIEnv *env, jclass c, jint i)
    {
      printf("%i\n",i);
    }
    

    Step 6. Within Visual Studio command promt, define the following variables:

    set JAVA_HOME= the path of JDK

    set include=%include%;%JAVA_HOME%\include;%JAVA_HOME%\include\win32

    Step 7. Generate DLL:

    cl /LD P.c P.def

    Step 8. Run the Java program:

    java P

    (Note: P.dll and P.class are located in the same directory)

    0 讨论(0)
  • 2021-01-12 15:53

    I had the same issue and the flag -Wl,-kill-at worked for me.

    0 讨论(0)
  • 2021-01-12 15:54

    Just guessing... Is your dll depends on another dll that is not on the path? MinGW modules usually depend on specific C runtime library.

    0 讨论(0)
  • 2021-01-12 16:10

    The problem is with the name compiler has generated: Java_com_Tune_add@16

    Use either of two

    gcc -Wl,-kill-at

    Or

    gcc -Wl,--add-stdcall-alias

    This will ensure generation of Java_com_Tune_add

    And then your method call will be successful.

    0 讨论(0)
  • 2021-01-12 16:12

    One possible source of the problem might be that you compiled the code using a C++ compiler, which uses a different [calling convention] than plain C. If thats the case then the solution would be to wrap the code for the method in a extern "C" block like this:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    JNIEXPORT jint JNICALL Java_com_Tune_add
    ...
    
    #ifdef __cplusplus
    }
    #endif
    
    0 讨论(0)
提交回复
热议问题