1. Create jnitest. Java:
Public class jnitest {
Static {
System. loadlibrary ("hello ");
}
Public native void say ();
Public static void main (string [] ARGs ){
System. Out. println ("I'm in Java ");
New jnitest (). Say ();
}
}
2. Compile jnitest. Java and generate the native header file:
Javac jnitest. Java
Javah-JNI jnitest
3. Create the hello. c file based on the function prototype in jnitest. h:
# Include <stdio. h>
# Include "jnitest. H"
Jniexport void jnicall java_jnitest_say (jnienv * ENV, jobject OBJ)
{
Printf ("I'm in C/C ++ \ n ");
}
4. To facilitate compilation, generate a MAKEFILE file:
Makefile:
. Phony: All
ALL:
Javac jnitest. Java
GCC -- shared-I/usr/lib/JVM/java-6-openjdk-i386/include hello. C-o libhello. So
5. Compile make and execute:
Java-djava. Library. Path =. jnitest
Note: If the libray path is not specified, an error is returned:
[Ancoo @ Ubuntu jnitest] $ Java jnitest
Exception in thread "Main" Java. Lang. unsatisfiedlinkerror: No hello in Java. Library. Path
At java. Lang. classloader. loadlibrary (classloader. Java: 1738)
At java. Lang. runtime. loadlibrary0 (runtime. Java: 823)
At java. Lang. system. loadlibrary (system. Java: 1028)
At jnitest. <clinit> (jnitest. Java: 4)
Cocould not find the main class: jnitest. program will exit.