Accessing Java Methods from Native Methods


// prompts for user's name
// and returns his/her fortune for the day

import java.lang.*;
import java.io.*;

class Iching3 {

  String msgs[] = new String[] {
    "Don King: Plain dealing will keep you out of trouble.",
    "IMF: The situation is about to change for the better.",
    "Clinton: Pay attention to small warnings.  Hard times lie ahead.",
    "Starr: Don't keep hitting your head against a stone wall.\nChannel your energy to attainable goals.",
    "Tyson: Overconfidence will lead to misadventure and regret.",
    "Bill Gates: For the moment, you are free of worry.",
    "Javasoft: Do what you have to do, but if it ain't broken, don't fix it.",
    "Smith: Honors, wealth, health and long life are in store as problems disappear.",
    "Sadam: Accept defeat and repent.  You will become at peace with yourself.",
    "Kiduk: Never give up.  Good times lie ahead." };

  private native void getfortune(String s, int cnt);

  static {
    System.loadLibrary("iching3");
  }

  private void findfortune(String s, int cnt) {
    if (cnt < 10) {
        if (msgs[cnt].startsWith(s))
            System.out.println("\n...fortune found!...\n\n" + msgs[cnt] + "\n\n");
        else {
            System.out.println(cnt + " : Java going to C");
            getfortune(s,cnt);
            System.out.println(cnt + " : Java returning from C");
        }
    }
    else
         System.out.println(cnt + " : Search limit exceeded. Java Gone!\n\n");
  }

  public static void main(String args[]) {

    Iching3 ich = new Iching3();
    byte buffer[]= new byte[255];

    // prompt for input
    System.out.println("\nPlease enter your name.");
    String prompt= new String ("Please enter your name.");
    try { System.in.read(buffer,0,255); }
    catch (Exception e) { System.out.println(e.toString()); }

    // pass input string to recursive method call
    String name= new String (buffer);
    ich.findfortune(name.trim(),0);

  }

}
 



  /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Iching3 */

#ifndef _Included_Iching3
#define _Included_Iching3
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Iching3
 * Method:    getfortune
 * Signature: (Ljava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_Iching3_getfortune
  (JNIEnv *, jobject, jstring, jint);

#ifdef __cplusplus
}
#endif
#endif
 
 



 
  #include "Iching3.h"
#include <stdio.h>
#include <stdlib.h>

extern "C" /* specify the C calling convention */

JNIEXPORT void JNICALL Java_Iching3_getfortune
  (JNIEnv *env, jobject obj, jstring s, jint cnt) {

  jclass cls = env->GetObjectClass(obj);
  jmethodID mid = env->GetMethodID(cls, "findfortune", "(Ljava/lang/String;I)V");
  if (mid == 0)  return;
  printf("In C, cnt = %d, about to enter Java\n", cnt);
  env->CallVoidMethod(obj, mid, s, cnt+1);
  printf("In C, cnt = %d, back from Java\n", cnt);

}
 
 
 

        "(argument-types)return-type"