Sunday 8 August 2010

Wrapping it all up




Since I'm going to be dealing with quite a lot of C++ code, it's interesting to know how one could use this functionality from a different programming language all in the cozy environment of one's own living room -the Eclipse IDE.

To get started, all we need is three ingredients: eclipse, SWIG and the SWIG plugin for eclipse called sKWash. For those unfamiliar with SWIG, according to their website, it is

"a software development tool that connects programs written in C and C++ with a variety of high-level programming languages."

Essentially you take some C or C++ code,

/* File : example.c */

#include
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(<ime);
return ctime(<ime);
}


write an interface file

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


build the module, i.e. for python:




unix % swig -python example.i
unix % gcc -c example.c example_wrap.c \
-I/usr/local/include/python2.1
unix % ld -shared example.o example_wrap.o -o _example.so


We can now use the Python module as follows :

>>> import example
>>> example.fact(5)
120
>>> example.my_mod(7,3)
1
>>> example.get_time()
'Sun Feb 11 23:01:07 1996'
>>>

This however involves the command line. The advantage of sKWash is that it provides a GUI to SWIG through eclipse. An example of its usage is shown here; which can of course be extended to more complicated code such as the conversion of whole libraries e.g. with Quantlib a C++ library for quantitative finance. The library can then be used from the desired programming language.

In brief, you create two C++ projects in eclipse, one to store your main code, the other as a container for the C++ wrapper generation. Then create a Java or "target language" project you require in eclipse, this acts as the container for wrapper code for the target language. In the final stage create a sKWash project and specify the C++ wrapper generation project and the target language project. Eclipse will then generate the interface files, then build the project. The wrapper code should now be displayed in your wrapper projects.

No comments:

Post a Comment