(a)
public class CSimpleJNI { private int nValue; public int getValue() { return nValue; } public void putValue(int newValue) { nValue = newValue; } public int transformValue(int someValue) { putValue(getValue() + someValue); return getValue(); } public native void nativeMethod(int param); }(b)
gcj -C CSimpleJNI.java(c)
gcjh -jni CSimpleJNI(d)
#include "CSimpleJNI.h" void Java_CSimpleJNI_nativeMethod(JNIEnv *env, jobject thisObj, jint param1) { jclass clsID; jmethodID mthdID; jmethodID putValueID; jint jiValue; (*env)->GetObjectClass(env, thisObj); mthdID = (*env)->GetMethodID(env, clsID, "getValue", "()I"); jiValue = (*env)->CallIntMethod(env, thisObj, mthdID); /* in real life, this would complex code */ jiValue++; mthdID = (*env)->GetMethodID(env, clsID, "putValue", "(I)V"); (*env)->CallVoidMethod(env, thisObj, mthdID, jiValue); }
Example 1: (a) Java class code stored in CSimpleJNI.java; (b) source Java code compiled into object code (bytecode); (c) extracting native method prototypes; (d) the C code.