SWIG

SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages, such as Java.

Tutorial

Let's see how to interface some C functions to Java. To install swig:

apt-get install swig

C code

Let's say you have them in a file 'example.c':

example.c

#include <time.h>
 
double My_variable = 3.0;
 
int fact(int n) {
    if (n <= 1) return 1;
    else return n*fact(n-1);
}
 
int my_mod(int x, int y) {
    return (x%y);
}
 
char *get_time() {
    time_t ltime;
    time(&ltime);
    return ctime(&ltime);
}

Interface file

Now, in order to add these files to your favorite language, you need to write an “interface file” which is the input to SWIG. An interface file for these C functions might look like this:

example.i

%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
 
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();

Building a Java module

To install the java compiler and the headers needed for the binding:

apt-get install sun-java5-jdk

Generate the Java bindings:

swig -java example.i
javac exampleJNI.java

To build the native library:

gcc -fpic -c example.c example_wrap.c -I/usr/lib/jvm/java-1.5.0-sun/include -I/usr/lib/jvm/java-1.5.0-sun/include/linux
gcc -shared example.o example_wrap.o -o libexample.so

Let's see an use example of the Java interface:

Test.java

public class Test {
    public static void main(String argv[]) {
        System.loadLibrary("example");
        System.out.println(exampleJNI.My_variable_get());
        System.out.println(exampleJNI.fact(5));
        System.out.println(exampleJNI.get_time());
    }
}

To compile it:

javac -classpath . Test.java

To run it:

java -Djava.library.path="." Test

An example output:

3.0
120
Fri Jun 22 20:32:37 2007

java/swig.txt · Last modified: 2010/08/12 by emilmont
CC Attribution-Noncommercial-Share Alike 3.0 Unported
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0