I'm using Ubuntu 10.10
So that's what I did.
Hello.java:
class Hello {
public native void sayHello();
static { System.loadLibrary("hellolib"); }
public static void main(String[] args){
Hello h = new Hello();
h.sayHello();
}
}
Then I ran the follwing commands:
dierre@cox:~/Scrivania/provajni$ javac Hello.java
dierre@cox:~/Scrivania/provajni$ javah -jni Hello
I've obtained Hello.class
and Hello.h
.
Hello.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */
#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Hello_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Then I created Hello.cpp:
#include <jni.h>
#include "Hello.h"
#include <iostream>
using namespace std;
JNIEXPORT void JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
cout << "Hello World!" << endl;
return;
}
And now the part where I think I screwed up. I was inspired by this guide (Compile the Dynamic or Shared Object Library section):
dierre@cox:~/Scrivania/provajni$ gcc -I"/usr/lib/jvm/java-6-sun/include" -I"/usr/lib/jvm/java-6-sun/include/linux" -o hellolib.so -shared -Wl,-soname,hello.so Hello.cpp -static -lc
that generates the file hellolib.so
But when I try to run it with java Hello
I have this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hellolib in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1734)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at Hello.<clinit>(Hello.java:4)
Could not find the main class: Hello. Program will exit.
I even tried this:
LD_LIBRARY_PATH=`pwd`
export LD_LIBRARY_PATH
with no results.
I know I'm doing something extremely stupid but I can't figure out what it is. The dynamic lib is generated with the -shared option, isn't it?
Update #1
I tried static { System.load("/home/dierre/Scrivania/provajni/hellolib.so"); }
to see if that worked but now:
Exception in thread "main" java.lang.UnsatisfiedLinkError: /home/dierre/Scrivania/provajni/hello.so: /home/dierre/Scrivania/provajni/hello.so: undefined symbol: _ZSt4cout
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1803)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1699)
at java.lang.Runtime.load0(Runtime.java:770)
at java.lang.System.load(System.java:1003)
at Hello.<clinit>(Hello.java:4)
Update #2
Ok, to solve the Update #1 problem I had to use g++
insted of gcc
, obviously. Still having trouble to use the load
method though. I can't seem to tell it the right path.