java.lang.UnsatisfiedLinkError 与 JNI 和 c

标签 java c java-native-interface

我见过很多 JNI 应用程序的例子。我自己试过一个并得到一个异常(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.

测试.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" ) ;
  }
 }

我已经编译了他的代码并用代码创建了一个 Test.h

javah -jni 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");

}

然后我用命令编译了c代码

gcc Test.c -o libTest.so

然后尝试使用命令运行 java 类

java -Djava.library.path=. Test

我遇到了异常

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,而不是hello。所以你的功能应该是:

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

此外,在编译源代码时,使用 -shared-fPIC 让 gcc 编译共享对象(而不是可执行文件):

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

编译为共享对象还意味着您可以从 Test.c 中删除 main 函数,它本来就不应该存在。

关于java.lang.UnsatisfiedLinkError 与 JNI 和 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090620/

相关文章:

java - 简单的 Android 应用程序在启动时崩溃

c - 在 C 中无效使用灵活数组 ERROR

c - 访问指针使其值改变

ant - 如果 makefile 失败则停止 ant 构建

java - 如何翻译 .java 源文件中的文本?

java - 从 Java 执行 PostgreSQL anon block

java - 需要常规表达式。对于属性顺序无关紧要的 html 元素

c - 在 C 中传递和修改二维数组的单行

java - JNI问题: calling in Java a Dll that uses a third party dll

java - SWIG支持void * C返回类型