SlideShare a Scribd company logo
1 of 20
Download to read offline
SWIG : An Easy to Use Tool for Integrating
     Scripting Languages with C and C++

                 David M. Beazley

           Department of Computer Science
                  University of Utah
             Salt Lake City, Utah 84112

                 beazley@cs.utah.edu


                     July 12, 1996


SWIG                      1                 1996 Tcl/Tk Workshop
Topics

•      What is SWIG?

•      Background

•      A quick tour

•      Applications

•      Limitations

•      Future directions



SWIG                         2      1996 Tcl/Tk Workshop
SWIG
(Simplified Wrapper and Interface Generator)
•      Compiles ANSI C/C++ declarations into bindings
       to interpreted languages

•      Supports most C/C++ datatypes

•      Simple C++ classes

•      Run-time type checking

•      Multiple files and modules

•      Automatically generates documentation

•      Currently supports Tcl, Python, Perl5, Perl4, Guile3
SWIG                            3                    1996 Tcl/Tk Workshop
Where am I coming from?
                 Big FLOPS

                             50-100 Gbytes            Dave’s
                             of Data                  Scripting
                                                      Language



                                                      SWIG
       3 years of
       frustration
                              @#**$!                  Prototype

                                             Tcl/Tk
       Lousy Tools             Dave’s   Python
                               Attitude
                               Problem
                                          Perl        SWIG
                              Ease
                              of Use
                                             Guile

SWIG                               4                       1996 Tcl/Tk Workshop
The Two Language Model
•      Two languages better than one

•      C/C++ (performance, number crunching, etc...)

•      Tcl (control, debugging, modules, user interface)

•      Unfortunately, need to write “wrapper” functions
                               Tcl Wrapper Function
                               int wrap_fact(ClientData clientData,
                                             Tcl_Interp *interp,
                                             int argc, char *argv[]) {
C function                         int arg0, result;
int fact(int n) {                  if (argc != 2) {
    if (n <= 1) return 1;                interp->result = "wrong # args";
    else return n*fact(n-1);             return TCL_ERROR;
}                                  }
                                   arg0 = atoi(argv[1]);
                                   result = fact(arg0);
                                   sprintf(interp->result,"%d",result);
                                   return TCL_OK;
                               }
SWIG                              5                           1996 Tcl/Tk Workshop
Automatic Wrapper Generation
•      Most languages have tools to generate wrapper code
•      Usually only support a single target language
•      Often use non-C syntax
•      Special purpose

SWIG Design Goals:
•      Use ANSI C/C++ syntax

•      Ease of use and flexibility

•      Language independence

•      Provide a parser and primitives. Allow everything
       else to be redefined.

SWIG                            6                  1996 Tcl/Tk Workshop
SWIG Overview
•      Interface file with               Interface File
       ANSI C/C++

•      Generic parser                          Parser

•      Target languages
       implemented as C++
                                   Code             Documentation
       classes                     Generator        Generator

•      Easy to extend
       (well mostly)
                                     Tcl                  HTML
                                     Python               LaTeX
•      Produces C/C++ source         Perl5                ASCII
       file as output.               Perl4
                                     Guile-iii


SWIG                           7                          1996 Tcl/Tk Workshop
A Simple Example
   fact.c                                    fact.i (SWIG Interface File)

       int fact(int n) {                      %module fact
          if (n <= 1) return 1;               %{
          else return(n*fact(n-1));           /* put header files here */
       }                                      %}
                                              extern int fact(int);




                                      SWIG
       unix> swig -tcl fact.i
       unix> gcc -c fact.c fact_wrap.c -I/usr/local/include
       unix> ld -shared fact.o fact_wrap.o -o fact.so
       unix> tclsh7.5
       % load ./fact.so
       % fact 6
       720
       %




SWIG                                    8                             1996 Tcl/Tk Workshop
Datatypes
•      All C/C++ built-in datatypes
          int, short, long, char, float, double, void


•      C/C++ pointers (used for everything else)

•      Pointers represented as character strings
          Vector *new_Vector(double x, double y, double z);

          % set v [new_Vector 1 2 3]
          _1008e248_Vector_p


•      Pointers are type-checked at run-time.
          % set v [new_Vector 1 2 3]
          % set n [new_Node]
          % set d [dot_product $v $n]
          Type error in argument 2 of dot_product.
          Expected _Vector_p
          %
SWIG                            9                       1996 Tcl/Tk Workshop
Functions, Variables, and Constants
•      Wrapping a C/C++ function
          double      foo(double a, int b, void *ptr);
          extern      Vector *transform(Matrix *m, Vector *v);
          int         MyClass::bar(double);


•      Linking with a global variable
          extern int Status;

•      Creating a constants
          #define MY_CONST      5
          enum swig {ALE, LAGER, PORTER};
          const double PI = 3.1415926;


•      Most “typical” C declarations can be handled.
          (but not functions taking arrays of pointers to functions, etc...)

SWIG                                    10                            1996 Tcl/Tk Workshop
SWIG and C++
•      Simple C++ classes and structs
•      Constructors, destructors, and virtual functions
•      Single public inheritance
•      C++ politely turned into C and wrapped (for now)
    %module list                      List *new_List(void) {
    %{                                    return new List;
    #include “list.h”                 }
    %}                                void delete_List(List *l) {
                                          delete l;
    class List {                      }
    public:                           void List_insert(List *this, char *i){
        List();                           this->insert(i);
        ~List();                      }
        void insert(char *item);      int List_length_get(List *this) {
        int length;                       return this->length;
        static void print(List *);    }
        ...                           int List_length_set(List *this, int v){
    };                                    return (this->length = v);
                                      }
                                      void List_print(List *l) {
                                          List::print(l);
                                      }

SWIG                                 11                          1996 Tcl/Tk Workshop
Controlling and Debugging C/C++
•      SWIG provides direct access to C/C++ variables,
       functions, constants, and classes.

•      Requires minimal or no code modifications

•      Can control existing C/C++ applications at a
       function level.

•      Tcl makes a great debugger.

•      Easily add Tcl/Tk to programs without worrying
       about messy details.

•      SWIG works particularly well in research applications

SWIG                           12                     1996 Tcl/Tk Workshop
Rapid Prototyping
•      Use SWIG for prototyping and experimentation

•      Example : OpenGL module
       •   Developed from OpenGL header files (gl.h, glu.h, aux.h)
       •   708 constants
       •   426 functions
       •   > 8000 lines of wrapper code
       •   Total development time : < 20 minutes

•      Sample code :
set light_ambient [newfv4 0.0 0.0 0.0 1.0]
glLightfv $GL_LIGHT0 $GL_AMBIENT $light_ambient
...
glClear $GL_COLOR_BUFFER_BIT
glPushMatrix
glRotatef 20.0 1.0 0.0 0.0
glPushMatrix
glTranslatef -0.75 0.5 0.0
glRotatef 90.0 1.0 0.0 0.0
auxSolidTorus 0.275 0.85
glPopMatrix
...
SWIG                                   13                            1996 Tcl/Tk Workshop
Building Modular Applications
•      SWIG can be used to build highly modular and
       programmable applications


•      SPaSM Molecular
       Dynamics Code

•      MATLAB

•      Data Analysis

•      Tcl/Tk




•      Don’t build a huge monolithic system---build
       components and reuse them.
SWIG                           14                     1996 Tcl/Tk Workshop
Language Independence
•      All languages have strengths and weaknesses

•      SWIG interface files are language independent

•      Language independent code re-use!

•      Example :
       •   Perl5 script to generate web statistics
       •   Uses MATLAB module developed for Tcl/Tk




SWIG                                15               1996 Tcl/Tk Workshop
Current Limitations
•      C++ support is incomplete (and will probably always
       be so)

•      No exception model

•      Numerical representation problems
       (particularly unsigned integers and longs)

•      No variable or optional arguments

•      Pointer model is extremely flexible, yet incompatible
       with most other Tcl extensions. (ie. File handles).

•      SWIG is still too difficult to extend (well, I think so).

SWIG                              16                      1996 Tcl/Tk Workshop
Conclusions
•      SWIG works with a wide variety of C code
       (and a reasonable subset of C++)

•      Particularly well-suited for research applications
       •   Scientists like the ease of use
       •   Works well with existing code
       •   Provides a direct mapping onto C/C++

•      Language independence is essential!
       •   There is no “best” scripting language
       •   Different applications have different needs

•      SWIG has proven to be remarkably reliable and
       powerful in a variety of applications

•      Much work remains!

SWIG                                   17                1996 Tcl/Tk Workshop
Future Work
•      SWIG 2.0

•      Support for more target languages
       •   Itcl
       •   Object Tcl
       •   ILU
       •   Java?


•      An exception model

•      More complete C/C++ parsing

•      Simplified extension mechanism

•      Using SWIG to do cool stuff

SWIG                          18           1996 Tcl/Tk Workshop
Acknowledgments
•      Users who have braved the first few releases
       and provided feedback

•      John Buckman (non-unix platforms)

•      Peter Lomdahl, Shujia Zhou, Brad Holian, Tim
       Germann, Niels Jensen (LANL).

•      John Schmidt, Kurtis Bleeker, Patrick Tullmann

•      The Scientific Computing and Imaging group

•      The Advanced Computing Laboratory (LANL)

•      DOE, NSF, NIH
SWIG                           19                     1996 Tcl/Tk Workshop
Blatant Advertisement
             SWIG is free and fully documented

Source code and user manual are available via
anonymous FTP:

       ftp://ftp.cs.utah.edu/pub/beazley/SWIG

The SWIG homepage:

       http://www.cs.utah.edu/~beazley/SWIG

The SWIG mailing list:

       swig@cs.utah.edu

SWIG                        20                   1996 Tcl/Tk Workshop

More Related Content

What's hot

Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
PyData
 

What's hot (20)

An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
 
Python in Action (Part 1)
Python in Action (Part 1)Python in Action (Part 1)
Python in Action (Part 1)
 
Mastering Python 3 I/O
Mastering Python 3 I/OMastering Python 3 I/O
Mastering Python 3 I/O
 
Python in Action (Part 2)
Python in Action (Part 2)Python in Action (Part 2)
Python in Action (Part 2)
 
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
 
Understanding the Python GIL
Understanding the Python GILUnderstanding the Python GIL
Understanding the Python GIL
 
Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
In Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter LockIn Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter Lock
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
 
The genesis of clusterlib - An open source library to tame your favourite sup...
The genesis of clusterlib - An open source library to tame your favourite sup...The genesis of clusterlib - An open source library to tame your favourite sup...
The genesis of clusterlib - An open source library to tame your favourite sup...
 
2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk User
 
Python Generator Hacking
Python Generator HackingPython Generator Hacking
Python Generator Hacking
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 

Similar to SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++

Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdfDatabase & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
InSync2011
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
DVClub
 

Similar to SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++ (20)

lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
Return of c++
Return of c++Return of c++
Return of c++
 
Golang
GolangGolang
Golang
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
tokyotalk
tokyotalktokyotalk
tokyotalk
 
C++primer
C++primerC++primer
C++primer
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdfDatabase & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
Database & Technology 1 _ Tom Kyte _ Efficient PL SQL - Why and How to Use.pdf
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
2 architecture anddatastructures
2 architecture anddatastructures2 architecture anddatastructures
2 architecture anddatastructures
 
ESL Anyone?
ESL Anyone? ESL Anyone?
ESL Anyone?
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++

  • 1. SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++ David M. Beazley Department of Computer Science University of Utah Salt Lake City, Utah 84112 beazley@cs.utah.edu July 12, 1996 SWIG 1 1996 Tcl/Tk Workshop
  • 2. Topics • What is SWIG? • Background • A quick tour • Applications • Limitations • Future directions SWIG 2 1996 Tcl/Tk Workshop
  • 3. SWIG (Simplified Wrapper and Interface Generator) • Compiles ANSI C/C++ declarations into bindings to interpreted languages • Supports most C/C++ datatypes • Simple C++ classes • Run-time type checking • Multiple files and modules • Automatically generates documentation • Currently supports Tcl, Python, Perl5, Perl4, Guile3 SWIG 3 1996 Tcl/Tk Workshop
  • 4. Where am I coming from? Big FLOPS 50-100 Gbytes Dave’s of Data Scripting Language SWIG 3 years of frustration @#**$! Prototype Tcl/Tk Lousy Tools Dave’s Python Attitude Problem Perl SWIG Ease of Use Guile SWIG 4 1996 Tcl/Tk Workshop
  • 5. The Two Language Model • Two languages better than one • C/C++ (performance, number crunching, etc...) • Tcl (control, debugging, modules, user interface) • Unfortunately, need to write “wrapper” functions Tcl Wrapper Function int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { C function int arg0, result; int fact(int n) { if (argc != 2) { if (n <= 1) return 1; interp->result = "wrong # args"; else return n*fact(n-1); return TCL_ERROR; } } arg0 = atoi(argv[1]); result = fact(arg0); sprintf(interp->result,"%d",result); return TCL_OK; } SWIG 5 1996 Tcl/Tk Workshop
  • 6. Automatic Wrapper Generation • Most languages have tools to generate wrapper code • Usually only support a single target language • Often use non-C syntax • Special purpose SWIG Design Goals: • Use ANSI C/C++ syntax • Ease of use and flexibility • Language independence • Provide a parser and primitives. Allow everything else to be redefined. SWIG 6 1996 Tcl/Tk Workshop
  • 7. SWIG Overview • Interface file with Interface File ANSI C/C++ • Generic parser Parser • Target languages implemented as C++ Code Documentation classes Generator Generator • Easy to extend (well mostly) Tcl HTML Python LaTeX • Produces C/C++ source Perl5 ASCII file as output. Perl4 Guile-iii SWIG 7 1996 Tcl/Tk Workshop
  • 8. A Simple Example fact.c fact.i (SWIG Interface File) int fact(int n) { %module fact if (n <= 1) return 1; %{ else return(n*fact(n-1)); /* put header files here */ } %} extern int fact(int); SWIG unix> swig -tcl fact.i unix> gcc -c fact.c fact_wrap.c -I/usr/local/include unix> ld -shared fact.o fact_wrap.o -o fact.so unix> tclsh7.5 % load ./fact.so % fact 6 720 % SWIG 8 1996 Tcl/Tk Workshop
  • 9. Datatypes • All C/C++ built-in datatypes int, short, long, char, float, double, void • C/C++ pointers (used for everything else) • Pointers represented as character strings Vector *new_Vector(double x, double y, double z); % set v [new_Vector 1 2 3] _1008e248_Vector_p • Pointers are type-checked at run-time. % set v [new_Vector 1 2 3] % set n [new_Node] % set d [dot_product $v $n] Type error in argument 2 of dot_product. Expected _Vector_p % SWIG 9 1996 Tcl/Tk Workshop
  • 10. Functions, Variables, and Constants • Wrapping a C/C++ function double foo(double a, int b, void *ptr); extern Vector *transform(Matrix *m, Vector *v); int MyClass::bar(double); • Linking with a global variable extern int Status; • Creating a constants #define MY_CONST 5 enum swig {ALE, LAGER, PORTER}; const double PI = 3.1415926; • Most “typical” C declarations can be handled. (but not functions taking arrays of pointers to functions, etc...) SWIG 10 1996 Tcl/Tk Workshop
  • 11. SWIG and C++ • Simple C++ classes and structs • Constructors, destructors, and virtual functions • Single public inheritance • C++ politely turned into C and wrapped (for now) %module list List *new_List(void) { %{ return new List; #include “list.h” } %} void delete_List(List *l) { delete l; class List { } public: void List_insert(List *this, char *i){ List(); this->insert(i); ~List(); } void insert(char *item); int List_length_get(List *this) { int length; return this->length; static void print(List *); } ... int List_length_set(List *this, int v){ }; return (this->length = v); } void List_print(List *l) { List::print(l); } SWIG 11 1996 Tcl/Tk Workshop
  • 12. Controlling and Debugging C/C++ • SWIG provides direct access to C/C++ variables, functions, constants, and classes. • Requires minimal or no code modifications • Can control existing C/C++ applications at a function level. • Tcl makes a great debugger. • Easily add Tcl/Tk to programs without worrying about messy details. • SWIG works particularly well in research applications SWIG 12 1996 Tcl/Tk Workshop
  • 13. Rapid Prototyping • Use SWIG for prototyping and experimentation • Example : OpenGL module • Developed from OpenGL header files (gl.h, glu.h, aux.h) • 708 constants • 426 functions • > 8000 lines of wrapper code • Total development time : < 20 minutes • Sample code : set light_ambient [newfv4 0.0 0.0 0.0 1.0] glLightfv $GL_LIGHT0 $GL_AMBIENT $light_ambient ... glClear $GL_COLOR_BUFFER_BIT glPushMatrix glRotatef 20.0 1.0 0.0 0.0 glPushMatrix glTranslatef -0.75 0.5 0.0 glRotatef 90.0 1.0 0.0 0.0 auxSolidTorus 0.275 0.85 glPopMatrix ... SWIG 13 1996 Tcl/Tk Workshop
  • 14. Building Modular Applications • SWIG can be used to build highly modular and programmable applications • SPaSM Molecular Dynamics Code • MATLAB • Data Analysis • Tcl/Tk • Don’t build a huge monolithic system---build components and reuse them. SWIG 14 1996 Tcl/Tk Workshop
  • 15. Language Independence • All languages have strengths and weaknesses • SWIG interface files are language independent • Language independent code re-use! • Example : • Perl5 script to generate web statistics • Uses MATLAB module developed for Tcl/Tk SWIG 15 1996 Tcl/Tk Workshop
  • 16. Current Limitations • C++ support is incomplete (and will probably always be so) • No exception model • Numerical representation problems (particularly unsigned integers and longs) • No variable or optional arguments • Pointer model is extremely flexible, yet incompatible with most other Tcl extensions. (ie. File handles). • SWIG is still too difficult to extend (well, I think so). SWIG 16 1996 Tcl/Tk Workshop
  • 17. Conclusions • SWIG works with a wide variety of C code (and a reasonable subset of C++) • Particularly well-suited for research applications • Scientists like the ease of use • Works well with existing code • Provides a direct mapping onto C/C++ • Language independence is essential! • There is no “best” scripting language • Different applications have different needs • SWIG has proven to be remarkably reliable and powerful in a variety of applications • Much work remains! SWIG 17 1996 Tcl/Tk Workshop
  • 18. Future Work • SWIG 2.0 • Support for more target languages • Itcl • Object Tcl • ILU • Java? • An exception model • More complete C/C++ parsing • Simplified extension mechanism • Using SWIG to do cool stuff SWIG 18 1996 Tcl/Tk Workshop
  • 19. Acknowledgments • Users who have braved the first few releases and provided feedback • John Buckman (non-unix platforms) • Peter Lomdahl, Shujia Zhou, Brad Holian, Tim Germann, Niels Jensen (LANL). • John Schmidt, Kurtis Bleeker, Patrick Tullmann • The Scientific Computing and Imaging group • The Advanced Computing Laboratory (LANL) • DOE, NSF, NIH SWIG 19 1996 Tcl/Tk Workshop
  • 20. Blatant Advertisement SWIG is free and fully documented Source code and user manual are available via anonymous FTP: ftp://ftp.cs.utah.edu/pub/beazley/SWIG The SWIG homepage: http://www.cs.utah.edu/~beazley/SWIG The SWIG mailing list: swig@cs.utah.edu SWIG 20 1996 Tcl/Tk Workshop