We start with Java class:
class YAHelloWorld
{
public native void sayHi(String name);
static
{
System.loadLibrary("YAHelloWorld");
}
public static void main(String[] args)
{
YAHelloWorld h = new YAHelloWorld();
h.sayHi("World");
}
}
Beside normal Java stuff we have request to load native library and forward declaration of native method. We save it as YAHelloWorld.java and compile it
javac YAHelloWorld.java
After that we invoke javah to create native header:
/usr/lib/jvm/java-7-oracle/bin/javah -jni YAHelloWorld
I was lazy to export path, so that is a reason for full path to javah. If you try without full path you may get following suggestion:
what is not really necessary. Content of generated YAHelloWorld.h is:
The first parameter, JNIEnv * is pointer to array of pointers of JNI functions, jobject is sort of this pointer and jstring is Java String. Now when we know all that we can write C++ implementation:
Beside normal C++ stuff we convert Java String to C++ string at the beginning and at the end we release both of them. Compilation looks like this:
g++ -shared -fPIC -I/usr/lib/jvm/java-7-oracle/include -I/usr/lib/jvm/java-7-oracle/include/linux YAHelloWorld.cpp -o libYAHelloWorld.so
and finally we execute our Hello World example like this:
java -Djava.library.path=. YAHelloWorld
That should produce familiar Hello World output. Not too difficult.
No comments:
Post a Comment