开发者

JNI and UnsatisfiedLinkError

开发者 https://www.devze.com 2023-04-06 16:03 出处:网络
I\'m doing my first steps with JNI and tried to write a simple Hello Java program, but it fails with this error:

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:

  1. Write Hello.java
  2. Compile Hello.java using javac Hello.java
  3. Create a header file using javah -jni Hello
  4. Write the Hello.c file
  5. 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"

  6. Execute Hello.class using java Hello

Thanks.

SOLUTION

Adding -Wl,--kill-at to the gcc command fixes the problem, according to this question here.

Thanks to A.H. for his help !


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 to java 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消