GCJ & the Cygnus Native Interface 
by Gene Sally

Example 1:
(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 2:

(a)
extern "Java"
{
  class CSimpleJNI;
};
class ::CSimpleJNI : public ::java::lang::Object
{
public:
  virtual jint getValue () { return nValue; }
  virtual void putValue (jint);
  virtual jint transformValue (jint);
  virtual void nativeMethod (jint);
  CSimpleJNI ();
private:
  jint nValue;
public:
  static ::java::lang::Class class$;
};

(b)
void CSimpleJNI::nativeMethod(jint param1) {
  jint value = getValue();
  // complex code omitted
  value++;
  putValue(value);
}


Listing One
(*env)->GetObjectClass(env, thisObj);
mthdID = (*env)->GetMethodID(env, clsID, "getValue", "()I");
jiValue = (*env)->CallIntMethod(env, thisObj, mthdID);

Listing Two
jclass rteClass;
jthrowable rteInstance;
rteClass = (*env)->FindClass(env, "java/lang/RuntimeException");
(*env)->ThrowNew(env, rteClass, "An exception thrown from JNI");
/* party members in good standing should return here */


Listing Three
try {
  // stuff
}
catch (CThrowMe e) {
  // do something !
}


Listing Four
  if ((rteException = (*env)->ExceptionOccurred(env)) != NULL) {
    if ((*env)->IsInstanceOf(env, rteException, rteClass) == JNI_TRUE) {
      printf("Caught the exception in native code\n");
      (*env)->ExceptionClear(env);
    }
  }





2


