Sunday, June 14, 2009

Using SWIG to cooperate Java with C++

Courtesy : SWIG Tutorial

Let the main file where my functions and variables are located is example.cxx
Write that source.

Then create an interface file .let example.i
where the previous module's variables and functions have to be declared.

Sample:


/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern type variableName;
extern type functionName(parameters);
%}

extern type variableName;
extern type functionName(parameters);
//end of file



Then create main java file.Let Its name is main.java


//main.java
public class main {
public static void main(String argv[]) {
System.loadLibrary("exampl
e");
System.out.println(example.getvariableName());
System.out.println(example.functionName(parameters));

}
}



commands:
$swig -c++ -java example.i
$g++ -c -fpic example.cxx
$g++ -c -fpic example_wrap.cxx -I/usr/lib/jvm/java-6-sun-1.6.0.06/include/ -I/usr/lib/jvm/java-6-sun-1.6.0.06/include/linux
$g++ -shared example.o example_wrap.o -o libexample.so
$export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
$javac main.java
$java main


You can make a shell script to automate the commands.

1 comment:

Anonymous said...

Nice dispatch and this mail helped me alot in my college assignement. Thank you on your information.