tludmetal
tludmetal

Reputation: 103

Exception in thread "main" java.lang.UnsatisfiedLinkError

I get the following explicit error when I test JNI in Java:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Italk2learn.hello()V
    at Italk2learn.hello(Native Method)
    at Italk2learn.main(Italk2learn.java:10)

There's no problem with the dll or paths because the static code of the my java class works well:

static {
        try {
            System.loadLibrary("Italk2learn");
        } catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
    }

And I think that it gets the library fine.

I use JVM 32 bits to compile and get the C++ header(javah) and MinGW32 for C++. In both cases I use eclipse for C++ and Java.

This is my code:

Java:

public class Italk2learn {

    public native void hello();

    public static void main(String[] args) {
        System.out.println("Hello World Java!");
        try {
            new Italk2learn().hello();
        } catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
    }
    static {
        try {
            System.loadLibrary("Italk2learn");
        } catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
    }
}

C++ :

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

JNIEXPORT void JNICALL Java_Italk2learn_hello(JNIEnv *, jobject) {
    printf("Hello World C++!\n");
#ifdef __cplusplus
    printf("__cplusplus is defined\n");
#else
    printf("__cplusplus is NOT defined\n");
#endif
    return;
}

Upvotes: 2

Views: 4508

Answers (2)

tludmetal
tludmetal

Reputation: 103

I have found the answer! It seems that when using JNI in Windows it looks for a function starting with _Java_ while in every other platform it looks for Java_. Why this is the case and not written in the documentation I don't know but it make everything work perfectly!

When javah creates the header file each function is named like Java_package_Class_method. The odd thing is that when compiled like this, JNI cannot find the right function for the native method and spits out errors, but if an underscore was added before Java then JNI would be able to find the function.

Upvotes: 4

parsifal
parsifal

Reputation: 49

If you're compiling with C++, you have to wrap your JNI methods with extern "C" to ensure that the compiler doesn't apply its own mangling:

extern "C" {
    JNIEXPORT void JNICALL Java_Italk2learn_hello(JNIEnv *, jobject) {
        // ..
    }
}

See: http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp224

Upvotes: 3

Related Questions