简体   繁体   中英

ECLIPSE - java.lang.UnsatisfiedLinkError while working with JNI

Hi everybody: I'm making practice with JNI on my Windows 7. My goal is to print at the Eclipse console a "Hello world" message using C's API.

I keep getting

Exception in thread "main" java.lang.UnsatisfiedLinkError: nativeStuff.HelloJNI.sayHello()V at nativeStuff.HelloJNI.sayHello(Native Method) at main.Init.main(Init.java:17)

On my project's Properties -> Libraries -> jre8 -> Native Library Location -> Edit -> Workspace I set nativeStuff as selected folder, since the library hello.dll is in there, but I keep getting the same error about UnsatisfiedLinkError .

Here's the source tree:

src(folder):
    main(package):
        Init.java
    nativeStuff(package):
        HelloJNI.java
        hello.dll
        HelloJNI.c
        nativeStuff_HelloJNI.h

Init.java:

public class Init {

    public static void main(String[] args) {
        System.out.println("Begin");
        new HelloJNI().sayHello(); // from the exception above
    }
}

HelloJNI.java:

public class HelloJNI {
    static {
        try {
            System.loadLibrary("hello");
        } catch(UnsatisfiedLinkError u) { // always from the exception above
            u.printStackTrace();
        } catch(SecurityException s) {
            s.printStackTrace();
        }
    }
    public native void sayHello();  
}

nativeStuff_HelloJNI.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class nativeStuff_HelloJNI */

#ifndef _Included_nativeStuff_HelloJNI
#define _Included_nativeStuff_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     nativeStuff_HelloJNI
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_nativeStuff_HelloJNI_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

and HelloJNI.c:

#include "jni.h"
#include <stdio.h>
#include "nativeStuff_HelloJNI.h"

// Implementation of native method sayHello() of HelloJNI class
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
   printf("Hello World!\n");
   return;
}

[Edit] : these are the commands I typed to get the files...

javac HelloJNI.java
javah -jni nativeStuff.HelloJNI
gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o hello.dll HelloJNI.c

System.loadLibrary is intended for system libraries, which are usually located in a jre subfolder. If you want to load a local library like in your example, use instead :

System.load("/path/to/your/lib.ext")

See jre javadoc


Finally, the error was : name of function had to be qualified : Java_nativeCode_HelloJNI_sayHello instead of Java_HelloJNI_sayHello inside .h and .c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM