Google

SWIG/Examples/java/simple/

Simple Java Example

$Header: /cvs/projects/SWIG/Examples/java/simple/Attic/index.html,v 1.1.2.1.2.1 2002/04/02 19:50:53 cheetah Exp $

This example illustrates how you can hook Java to a very simple C program containing a function and a global variable.

The C Code

Suppose you have the following C code:
/* File : example.c */

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}

The SWIG interface

Here is a simple SWIG interface file:
/* File: example.i */
%module example

extern int gcd(int x, int y);
extern double Foo;

Compilation

  1. swig -java example.i

  2. Compile example_wrap.c and example.c to create the extension libexample.so (unix).

Using the extension

Click here to see a program that calls our C functions from Java.

Compile the java files example.java and main.java to create the class files example.class and main.class before running main in the JVM. Ensure that the libexample.so file is in your LD_LIBRARY_PATH before running. For example:

export LD_LIBRARY_PATH=. #ksh 
javac *.java
java main

Key points

  • Use the loadLibrary statement from java to load and access the generated java classes. For example:
    System.loadLibrary("example");
    
  • C functions work just like Java functions. For example:
    int g = example.gcd(42,105);
    
  • C global variables are accessed through get and set functions in the module class. For example:
    double a = example.get_Foo();
    example.set_Foo(20.0);