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 would 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