BackSlash
BackSlash

Reputation: 22233

java.lang.UnsatisfiedLinkError using native interface

I have this cpp file:

//pkgnative_tries__native_NativeSystem.cpp
#include <pkgnative_tries__native_NativeSystem.h>
#include<iostream>
using namespace std;

extern "C"
JNIEXPORT void JNICALL Java_pkgnative_tries__1native_NativeSystem_println
  (JNIEnv *env, jobject obj, jstring javaString)
{
    //Get the native string from javaString
    const char *nativeString = env->GetStringUTFChars(javaString, 0);
    cout << nativeString;

    env->ReleaseStringUTFChars(javaString, nativeString);
}

pkgnative_tries__native_NativeSystem.h:

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

#ifndef _Included_pkgnative_tries__native_NativeSystem
#define _Included_pkgnative_tries__native_NativeSystem
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     pkgnative_tries__native_NativeSystem
 * Method:    println
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_pkgnative_tries__1native_NativeSystem_println
  (JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

This is the java class:

import java.io.File;

public class NativeSystem {
    static {
        try {
            System.load(new File(NativeSystem.class.getResource("native_files/pkgnative_tries__native_NativeSystem.dll").toURI()).getPath());
        } catch (Exception e) {
            System.err.println("Error");
            e.printStackTrace();
        }
    }
    public static native void println(String obj);
}

When i call NativeSystem.println("abc"); it shows

Exception in thread "main" java.lang.UnsatisfiedLinkError: NativeSystem.println(Ljava/lang/String;)V
    at NativeSystem.println(Native Method)
    at NativeTries.main(NativeTries.java:19)
Java Result: 1

Does anyone know why? I'm sure the dll is loaded, the catch block in the static block in NativeSystem doesn't execute. I've never encountered this before. How can i fix it?

Upvotes: 2

Views: 2680

Answers (2)

Maveňツ
Maveňツ

Reputation: 1

In your case the line "native_files/pkgnative_tries__native_NativeSystem.dll" is seems messy, please check it.

I have resolved the same type of issue by adding

System.loadLibrary("your library name");

To each method where they are needed and please also verify that the path of library is correct.

Pls ref this for further information. UnsatisfiedLinkError in native method

Thanks

Upvotes: 0

user2773289
user2773289

Reputation: 462

C++ does mangle the names of functions in the DLLs, if you are on windows you can use dumpbin to see what the function name looks like in dll.

Upvotes: 1

Related Questions