Calling C Library Routines from Java
by Mick Pont

Listing One
// The Bessel.java file
public class Bessel
{
  // Declaration of the Native (C) function
  private native double bessely0(double x);
  static
    {
      // The runtime system executes a class's static initializer 
      // when it loads the class.
      System.loadLibrary("CJavaInterface");
    }
  // The main program
  public static void main(String[] args)
    {
      double x, y;
      int i;
      /* Check that we've been given an argument */
      if (args.length != 1)
        {
          System.out.println("Usage: java Bessel x");
          System.out.println("  Computes Y0 Bessel function of argument x");
          System.exit(1);
        }
      // Create an object of class Bessel
      Bessel bess = new Bessel();
      /* Convert the command line argument to a double */
      x = new Double(args[0]).doubleValue();
      System.out.println();
      System.out.println("Calls of Y0 Bessel function routine bessely0");
      for (i = 0; i < 10; i++)
        {
          /* Call method bessely0 of object bess */
          y = bess.bessely0(x);
          System.out.println("Y0(" + x + ") is " + y);
          /* Increase x and repeat */
          x = x + 0.25;
        }
    }
}


Listing Two

/* The Bessel.h file generated from the Bessel class by the javah tool. */
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Bessel */
#ifndef _Included_Bessel
#define _Included_Bessel
#ifdef __cplusplus
extern "C" {
#endif
/* Class:     Bessel
 * Method:    bessely0
 * Signature: (D)D
 */
JNIEXPORT jdouble JNICALL Java_Bessel_bessely0
  (JNIEnv *, jobject, jdouble);
#ifdef __cplusplus
}
#endif
#endif


Listing Three

/* The BesselImp.c file, which implements the native function */
#include <jni.h>      /* Java Native Interface headers */
#include "Bessel.h"   /* Auto-generated header created by javah -jni */
#include <math.h>     /* Include math.h for the prototype of function y0 */

/* Our C definition of the function bessely0 declared in Bessel.java */
JNIEXPORT jdouble JNICALL
Java_Bessel_bessely0(JNIEnv *env, jobject obj, jdouble x)
{
  double y;
  /* Call Y0(x) Bessel function from standard C mathematical library */
  y = y0(x);
  return y;
}


Listing Four

// Output when running the Java Bessel program
Calls of Y0 Bessel function routine bessely0
Y0(1.0) is 0.08825696421567694
Y0(1.25) is 0.2582168515945407
Y0(1.5) is 0.38244892379775886
Y0(1.75) is 0.465492628646906
Y0(2.0) is 0.5103756726497451
Y0(2.25) is 0.5200647624572782
Y0(2.5) is 0.4980703596152316
Y0(2.75) is 0.4486587215691318
Y0(3.0) is 0.3768500100127903
Y0(3.25) is 0.2882869026730869





2


