Search code examples
java-native-interfaceunsatisfiedlinkerror

JNI UnsatisfiedLinkError for Ubuntu;


I've looked around on stackoverflow for similar problems, but none of the solutions I've found seem to be working for me. I am on a Linux/Ubuntu machine. I'm just practising JNI but I get this error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: nativetest.sayHello(Ljava/lang/String;)Ljava/lang/String;
at nativetest.sayHello(Native Method)
at nativetest.main(nativetest.java:8)

I have provided my .c, .h, and .java file.

.java file:

public class nativetest
{
System.loadLibrary("nativetest");

public native String sayHello(String s);

 public static void main(String[] argv)
 {
 String retval = null;
 nativetest nt = new nativetest();
 retval = nt.sayHello("Hi");
 System.out.println("Invocation returned " + retval);
 }
}

.c file:

#include "nativetest.h"
#include <stdio.h>
#include <jni.h>
#include <stdlib.h>

JNIEXPORT jstring JNICALL Java_nativetest_sayHello(JNIEnv *env, jobject thisobject, jstring js)
{
  return js;
}

.h file:

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

#ifndef _Included_nativetest
#define _Included_nativetest
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     nativetest
 * Method:    sayHello
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_nativetest_sayHello
  (JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

I used these commands to generate the .h file, compile/generate the .so file, and run:

javac nativetest.java

javah -jni nativetest

gcc --shared -o libnativetest.so -I/usr/lib/jvm/java-7-openjdk-amd64/include -I/usr/lib/jvm/java-7-openjdk-amd64/include/linux nativetest.c

java -Djava.library.path=. nativetest

I am currently in the directory with the libnativetest.so file and all my .c, .java, and .h files.

Any help would be appreciated.


Solution

  • Okay, turns out the call to

    System.loadLibrary("nativetest");
    

    should be static:

    static{
    System.loadLibrary("nativetest");
    }
    

    I was also making mistakes on recompiling using javac. I am quite new to Linux :)