SWIG
From CSWiki
This is the wiki page for SWIG( Simplified Wrapper and Interface Generator ).
Contents |
[edit] Conceptual model
[edit] Concepts and objects
SWIG is a tool that lets users connect C++/C with a lot of other programming languages, for examples, Perl, PHP, Python, Tcl, Ruby and PHP. It also connects C++/C with java, which the following article will be focusing on.
[edit] Operations
From the name of SWIG(Simplified Wrapper and Interface Generator), we can see that they want to make the connection simple. Let's see if it is really simple.
In order to use libraries written in C++/C, java programmers usually use the JNI( Java Native Interface) to communicate with C++/C. However, doing JNI is not an easy task if you are new to this field. It consists of much low level processing so it will not look like normal java programming. The idea of SWIG is to make this task simple. It works as the following way:
1. Assume we have a C file: example.c. 2. Then we write an example.i file, which is an interface file. 3. Use SWIG to compile example.i and generate example_wrap.c, example.java, and exampleJNI.java. 4. Then compile example.c and example_wrap.c into a DLL file(Assume we are using windows). 5. Then write our own java program to call this library. 6. Compile all the java files. 7. Run the java main program.
[edit] Prerequisites
Because we are focusing on Java and C++/C, let's assume you meet the following requirement:
1. JDK(the latest version is 6.0) 2. C++/C compiler(for example, visual C++)
then do the following:
1. Download the SWIG from swig home page. 2. Unzip the file to the location you prefer. 3. Add %swig folder% to the environment variable path. 4. Add the path, which points to jni.h, to environment variable JAVA_INCLUDE. 5. Add the path, which points to javac.exe, to environment variable JAVA_BIN.
then you are ready to run.
[edit] How accessed/used
- First write a C/C++ program or maybe you already have one.
- Then write a interface file, for instance, example.i(swig will read this .i file). It will look like this:
/* File : example.i */
%module example
%inline %{
extern int function_name_in_the_C_file(int x, int y);
extern double global_variable;
%}
- Use swig to compile the example.i file. In the command line, type in:
swig -java example.i
- It will generate example_wrap.c, example.java, and exampleJNI.java.
- Then compile example_wrap.c and the C file you have to the DLL file.
- Then write your java main program to call this dll library. The following should be place in the code in order to call the library "example".
static {
try {
System.loadLibrary("example");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
- Compile all the java code.
- Run the program in the command line by type in:
java -Djava.library.path=%the location of the dll file% The_main_program_name
- Then you are done.

