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

故事扮演 提交于 2019-12-01 05:48:46

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

kool

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.

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

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!