Sunday, April 19, 2009

Swig

I have recently been playing around with a new interface compiler tool called SWIG
SWIG stands for SIMPLIFIED WRAPPER AND INTERFACE GENERATOR .We are using it to rapidly generate JNI code for us so that we can use it to talk to C++ through Java. Most of the examples provided in the examples are very trivial but to do more complex things the best way would be to download the code and look through the examples. I will start now with a very simple example.....We model a book class that has a vector of chapters.

class Chapter //With copy constructor
{
private:
char *name;
public:
Chapter()
{
name = new char[20];
}
char* getName(){
return name;
}
void setName(char *nam){
strcpy(name,nam);
}};


class Book //With copy constructor
{
private:
char *name;
std::vector chapter_;
public:
void addChapter(Chapter *chap){
chapter_.push_back(chap);
}
std::vector getChapter(){return chapter_;}

Book()
{
name = new char[20];
}
};


We would talk to Book class in c++ using Java.Swig generates for us the glue code to enable us to do so .To generate the swig glue code we must first create an interface file

Step 1)

/* File : example.i */
%module testModuleAPI

%include cpointer.i
%include "arrays_java.i"
%include "std_string.i"
%include "std_vector.i"
%include "chapter.h"
%{
#include "chapter.h"

%}
namespace std
{
%template(ChapterVector) vector;
};
%include "book.h"


%{
#include "book.h"

%}



Step2) Create swig artifacts
/cygdrive/c/swig-1.3.38/preinst-swig -c++ -java -package test -outdir ./test ./test/test.i


Step 3)Compile c++ classes and create a library file
g++ -mno-cygwin -I /cygdrive/c/jdk1.6.0_12/include -I /cygdrive/c/jdk1.6.0_12/include/win32 -Wl,--add-stdcall-alias -shared -o ./test/test.dll ./test/*.cxx


Step 4)Write java class to test c++

public class RunSample {
static {
System.load("C:\\workspace\\swigSamples\\src\\test\\abc.dll");
}
public static void main(String args[]){
Chapter chap=new Chapter();
chap.setName("test");
Book book=new Book();
book.addChapter(chap);
ChapterVector vec=book.getChapter();
long val=vec.size();
System.out.println("Value "+val);
Chapter chap2=vec.get(0);
System.out.println("Name >>>>"+chap2.getName());

}
}