I'm doing my first steps with JNI and tried to write a simple Hello Java program, but it fails with this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: HelloJava.dostuff()V
at HelloJava.dostuff(Native Method)
at HelloJava.main(HelloJava.java:12)
This is my Java class:
class HelloJava {
private native void dostuff();
static {
System.loadLibrary("HelloJavaDLL");
}
public static void main(String[] args) {
System.out.println("This is from java.");
HelloJava j = new HelloJava();
j.dostuff();
}
}
The HelloJava.c is generated using javah -jni HelloJava
.
The C implementation looks like this:
#include <stdio.h>
#include <jni.h&g开发者_开发技巧t;
#include "HelloJava.h"
JNIEXPORT void JNICALL Java_HelloJava_dostuff
(JNIEnv *env, jobject this)
{
printf("And this comes from C ! :)\n");
}
I compiled it on Windows using gcc to a shared library (.dll).
Now running the Java .class File the Exception from above occurs. Can you tell me why this error appears ?
And by-the-way, can you tell me how I can use JNI with C++ ?
UPDATE
Maybe you want to try it yourself ? I really can't find the issue.Here is a link to MediaFire where you can download a .zip file containing all files (event the compiled ones).
The retried everything but it's still the same issue.
Theese are the steps I did:- Write Hello.java
- Compile Hello.java using
javac Hello.java
- Create a header file using
javah -jni Hello
- Write the Hello.c file
- Compile the Hello.c file using
gcc Hello.c -shared -o Hello.dll -I"C:\Java\jdk1.7.0\include" -I"C:\Java\jdk1.7.0\include\win32"
- Execute Hello.class using
java Hello
Thanks.
SOLUTION
Adding -Wl,--kill-at
to the gcc command fixes the problem, according to this question here.
Please check:
- The filename of your library is
HelloJavaDLL.dll
(on Windows) - The directory of the DLL is either in the library search path (i.e.
PATH
environment variable) or supplied tojava
with-Djava.library.path=C:\WhereEverItIs
.
The second question: JNI supports both C and C++ right out of the box. If you look into the generated header file and in the jni.h
file you will see this.
精彩评论