Beginner guide to Swig. SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates the wrappers needed to access those declarations from other languages including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes.
Create a "c" or "cpp" program file
- ex:
example.c
- Add few methods
Create a SWIG interface ".i" file
- ex:
example.i
- Add function prototypes and variable declarations
Use swig
command to generate java
file
swig -java example.i
- This will generate 3 files
- example_wrap.c
- example.java
- exampleJNI.java
- compile
example.c
andexample_wrap.c
using
gcc -fPIC -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include/ -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include/linux -shared -o libexample.so example.c example_wrap.c
- This will output the shared lib
libexample.so
- Create a
Java
client to code access theC
program - ex:
TestClient.java
- compile the java file by
javac TestClient.java
- run the program by
java -Djava.library.path=. TestClient