我见过很多 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/