Getting started with SWIG with Java

I bumped into an error while trying out one simple example involving using the java_modular interface of shogun. It seems that the swig file is not updated. Anyways, more about that later but I started to get to know swig a bit. Here is how I got it worked under GNU/Linux 3.6.10-2.fc16.x86_64 with C. This tutorial might be helpful.

Step 1 – Creating the source file

I created an example.c file as shown –

/* File : example.c */

 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;
     return ctime(&ltime);

Step 2 – Creating the interface file

I created an interface file which is needed by swig (actually copied and pasted from the tutorial, will have to find out how it works) as below –

/* 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();

Step 3 – Run swig on the interface file.

swig -java example.i

This creates three files, example_wrap.c, example_wrap.c. More details about these files later.

Step 4 – Compile the source file with the wrapper, jni.h and jni_md.h

We need to locate jni.h and jni_md.h first. In my system the path was


Then I compiled with the -fpic option in order to create a shared library. (See here)

gcc -fpic -c example.c example_wrap.c -I/usr/lib/jvm/java-1.6.0-openjdk- -I/usr/lib/jvm/java-1.6.0-openjdk-

This creates the object files example.o, example_wrap.o.

Step 5 – Creating the shared link library

I created an with –

ld -shared example.o example_wrap.o -o

[Optional Step – Create a jar with the classes]

To be written

Step 6 – Create the java file

I created the java file with main class containing a System.load call

// filename
public class main {
  public static void main(String argv[]) {

Step 7 – Compile the java file with classpath

The file should be compiled with classpath option

javac -cp '.:/path/to/swig/generated/class/files/'

Step 8 – Run the example with added library path

While running, the path of should be provided with the Djava.library.path=”..”

java -cp '.:/path/to/swig/generated/class/files/' -Djava.library.path=".:/path/to/"

Feels so good when you finally see the output

Wed Feb 20 11:52:57 2013

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s