Tested on centos 5.8
Step 1: declare a native function in the Java source file
public class AddMe{ static { System.loadLibrary("hello"); } public native void sum(int a, int b); public static void main(String[] args){ AddMe am = new AddMe(); am.sum(2, 5); }}
Step 2: Compile the Java class
javac AddMe.java
Step 3: generate the C header file
javah -jni AddMe
You will find the "addme. H" file in the current working directory
Step 4: implement the C function "sum" (by JNI naming convention the function name wocould be java_addme_sum)
We create a C source file called "addme. c"
#include "AddMe.h"#include <stdio.h>JNIEXPORT void JNICALL Java_AddMe_sum (JNIEnv *env, jobject obj, jint a, jint b){ jint result = 0; result = a + b; printf("hello world %d\n", result);}
Step 5: Compile the C code and generate a share library "libhello. So" (it must have the name libhello so that system. loadlibrary ("hello") can dynamically load the Library)
gcc -fPIC -I/usr/lib/jvm/java/include -o libhello.so -shared ./addme.c
Step 6: run the Java bytecode
java -Djava.library.path=. AddMe
Then you can see "Hell world 7" printed on Console