SlideShare a Scribd company logo
1 of 21
Download to read offline
Perl-C/C++ Integration with Swig

                                                   Dave Beazley
                                          Department of Computer Science
                                               University of Chicago
                                                Chicago, IL 60637
                                             beazley@cs.uchicago.edu


                                                              August 23, 1999



O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Roadmap


 What is Swig?

 How does it work?

 Why would you want to use it?

 Advanced features.

 Limitations and rough spots.

 Future plans.




O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
What is Swig?
 It’s a compiler for connecting C/C++ with interpreters

 General idea:
   • Take a C program or library
   • Grab its external interface (e.g., a header file).
   • Feed to Swig.
   • Compile into an extension module.
   • Run from Perl (or Python, Tcl, etc...)
   • Life is good.




O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Swig, h2xs and xsubpp
 Perl already has extension building tools
    • xsubpp
    • h2xs
    • Makemaker
    • Primarily used for extension building and distribution.

   Why use Swig?
    • Much less internals oriented.
    • General purpose (also supports Python, Tcl, etc...)
    • Better support for structures, classes, pointers, etc...

 Also...
    • Target audience is primarily C/C++ programmers.
    • Not Perl extension writers (well, not really).

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
How does it work?
     Typical C program                                            Header file
             main()                                                extern int foo(int n);
                                                                   extern double bar;
             Functions                                             struct Person {
             Variables                                                 char *name;
             Objects                                                   char *email;
                                                                   };


     Interesting C Program                                        Swig Interface
                  Perl                                             %module myprog
                                                     Swig
                                                                   %{
             Wrappers                                              #include "myprog.h"
                                                                   %}
             Functions                                             extern int foo(int n);
             Variables                                             extern double bar;
             Objects                                               struct Person {
                                                                       char *name;
                                                                       char *email;
                                                                   };



O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Swig Output
 Swig converts interface files into C wrapper code
   • Similar to the output of xsubpp.
   • It’s nasty and shouldn’t be looked at.

 Compilation steps:
   • Run Swig
   • Compile the wrapper code.
   • Link wrappers and original code into a shared library.
   • Cross fingers.

 If successful...
     • Program loads as a Perl extension.
     • Can access C/C++ from Perl.
     • With few (if any) changes to the C/C++ code (hopefully)

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Example
     C Code                                                          Perl
     int foo(int, int);                                               $r = foo(2,3);
     double Global;                                                   $Global = 3.14;
     #define BAR 5.5                                                  print $BAR;
     ...                                                              ...


 Perl becomes an extension of the underlying C/C++ code
    • Can invoke functions.
    • Modify global variables.
    • Access constants.

 Almost anything that can be done in C can be done from Perl
    • We’ll get to limitations a little later.


O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Interface Files
 Annotated Header Files

 Module name                                                      %module myprog

 Preamble                                                         %{
         • Inclusion of header files                              #include "myprog.h"
         • Support code                                           %}
         • Same idea as in yacc/bison

 Public Declarations                                              extern int foo(int n);
         • Put anything you want in Perl here
                                                                  extern double bar;
         • Converted into wrappers.                               struct Person {
         • Usually a subset of a header file.
                                                                      char *name;
                                                                      char *email;
 Note : Can use header files                                      };
         • May need conditional compilation.


O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Supported C/C++ Features
 Functions, variables, and constants
         • Functions accessed as Perl functions.
         • Global variables mapped into magic Perl variables.
         • Constants mapped into read-only variables.

 All C/C++ datatypes supported except:
         •   Pointers to functions and pointers to arrays (can fix with a typedef).
         •   long long and long double
         •   Variable length arguments.
         •   Bit-fields (can fix with slight modifications in interface file).
         •   Pointers to members.

 Structures and classes
         •   Access to members supported through accessor functions.
         •   Can wrap into Perl "classes."
         •   Inheritance (including multiple inheritance).
         •   Virtual and static members.

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Pointers
 Swig allows arbitrary C pointers to be used
   • Turned into blessed references

 Pointers are opaque
    • Can freely manipulate from Perl.
    • But can’t peer inside.

 Type-checking
    • Pointers encoded with a type to perform run-time checks.
    • Better than just casting everything to void * or int.

 Works very well with C programs
   • Structures, classes, arrays, etc...
   • Besides, you can never have too many pointers...

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Shadow Classes
 Structures and classes can be hidden behind a Perl class:
           C/C++ struct or class                                  C accessor functions
            class Foo {                                            Foo *new_Foo();
            public:                                                void delete_Foo(Foo *f);
               int x;                                              int Foo_x_get(Foo *f);
               Foo();                                              int Foo_x_set(Foo *f, int x);
               ~Foo();                                             int Foo_bar(Foo *f, int);
               int bar(int);                                       ...
               ...
            }

           Perl wrappers                                          Use from a Perl script
             package Foo;                                          $f = new Foo;
             sub new {                                             $f->bar(3);
               return new_Foo();                                   $f->bar{’x’} = 7;
             }                                                     del $f;
             sub DESTROY {
                delete_Foo();
             }
             ...etc...


O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Swig Applications
 User interfaces
   • Use Perl, Python, or Tcl as the interface to a C program.
   • This is particularly useful in certain applications.

 Rapid prototyping and debugging of C/C++
   • Use scripts for testing.
   • Prototype new features.

 Systems integration
    • Use Perl, Python, or Tcl as a glue language.
    • Combine C libraries as extension modules.

 The key point:
   • Swig can greatly simplify these tasks.

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Interface Building Problems
 Swig attempts to be completely automated.
   • "Wrap it and forget it"

 Problem : C/C++ code varies widely (and may be a mess)
    • Pointer ambiguity (arrays, output values, etc...).
    • Preprocessor macros.
    • Error handling (exceptions, etc...)
    • Advanced C++ (templates, overloading, etc...)

 Other problems
    • A direct translation of a header file may not work well.
    • Swig only understands a subset of C.
    • May want to interface with Perl data structures.


O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Parsing Problems
 Swig doesn’t understand certain declarations
   • Can remove with conditional compilation or comments

 Example:
     int foo(char *fmt, ...);                                     // int foo(char *fmt, ...);

     int bar(int (*func)(int));                                   #ifndef SWIG
                                                                  int bar(int (*func)(int));
     #define Width(im) (im->width)                                #endif

                                                                  int Width(Image *im);


 A Swig interface doesn’t need to match the C code.
    • Can cut out unneeded parts.
    • Play games with typedef and macros.
    • Write helper functions.

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Advanced Features
 Typemaps
    • A technique for modifying Swig’s type handling.

 Exception Handling
    • Converting C/C++ errors into Perl errors.

 Class and structure extension
    • Adding new methods to structures and classes
    • Building O-O interfaces to C programs.

 This is going to be a whirlwind tour...




O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Typemap Example
 Problem : Output values
 void getsize(Image *im, int *w, int *h) {
      *w = im->width;
      *h = im->height;
 }

 Solution: Typemap library
 %include typemaps.i
 %apply int *OUTPUT { int *w, int *h };
 ...
 void getsize(Image *im, int *w, int *h);

 From Perl:
 ($w,$h) = getsize($im);

 Note: There is a lot of underlying magic here (see docs).

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Exception Handling
 Problem : Converting C errors into Perl errors
 int foo() {
      ...
      throw Error;
      ...
 };

 Solution (place in an interface file):
 %except(perl5) {
    $function
    if (Error) {
          croak("You blew it!");
    }
 }

 Exception code gets inserted into all of the wrappers.

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Class Extension
 An interesting hack to attach methods to structs/classes
   typedef struct {
       int width;
       int height;
       ...
   } Image;
                                                                  $im = new Image;
   %addmethods Image {                                            $im->plot(30,40,1);
       Image(int w, int h) {
           return CreateImage(w,h);                               print $im->{’width’};
       }                                                          etc ...
       ~Image() {
           free(self);
         }
        void plot(int x, int y, int c) {
              ImagePlot(self,x,y,z);
         }
         ...
   }




O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Limitations
 Parsing capability is limited
    • Some types don’t work:
          int (*func[10])(int, double);
          int *const a;
          int **&a;
    • No macro expansion (Swig1.1)
    • A number of advanced C++ features not supported.

 Not all C/C++ code is easily scriptable
    • Excessive complexity.
    • Abuse of macros and templates.

 Better integration with Perl
    • Support for MakeMaker and other tools.
    • Windows is still a bit of a mess.
O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Future Plans
 Swig1.1 is maintained, but is not the focus of development
   • Daily maintenance builds at
          http://swig.cs.uchicago.edu/SWIG

 Swig2.0
   • A major rewrite and reorganization of Swig.
   • Primary goal is to make Swig more extensible.

 Highlights
    • Better parsing (new type system, preprocessing, etc...)
    • Plugable components (code generators, parsers, etc...)
    • Substantially improved code generation.
    • Release date : TBA.


O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999
Availability
 Swig is free.
   • www.swig.org (Primary)
   • swig.cs.uchicago.edu (Development)
   • CPAN

 Compatibility
   • Most versions of Perl (may need latest Swig however).
   • Unix, Windows.

 Acknowledgments
   • David Fletcher, Dominique Dumont, and Gary Holt.
   • Swig users who have contributed patches.
   • University of Utah
   • Los Alamos National Laboratory

O’Reilly Open Source Conference 3 0   - Swig -   August 23 1999

More Related Content

What's hot

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.0David Beazley (Dabeaz LLC)
 
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 LockDavid Beazley (Dabeaz LLC)
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIDavid Beazley (Dabeaz LLC)
 
PyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialPyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialJustin Lin
 
Ry pyconjp2015 karaoke
Ry pyconjp2015 karaokeRy pyconjp2015 karaoke
Ry pyconjp2015 karaokeRenyuan Lyu
 
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...Rodrigo Senra
 
Beating the (sh** out of the) GIL - Multithreading vs. Multiprocessing
Beating the (sh** out of the) GIL - Multithreading vs. MultiprocessingBeating the (sh** out of the) GIL - Multithreading vs. Multiprocessing
Beating the (sh** out of the) GIL - Multithreading vs. MultiprocessingGuy K. Kloss
 
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...Arnaud Joly
 
Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System AdministratorsRoberto Polli
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekingeProf. Wim Van Criekinge
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETL
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETLSimple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETL
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETLRomain Dorgueil
 
A (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIA (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIEdward B. Rockower
 
閒聊Python應用在game server的開發
閒聊Python應用在game server的開發閒聊Python應用在game server的開發
閒聊Python應用在game server的開發Eric Chen
 

What's hot (20)

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)
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
 
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
 
Python Generator Hacking
Python Generator HackingPython Generator Hacking
Python Generator Hacking
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard II
 
Interfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIGInterfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIG
 
PyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialPyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 Tutorial
 
Ry pyconjp2015 karaoke
Ry pyconjp2015 karaokeRy pyconjp2015 karaoke
Ry pyconjp2015 karaoke
 
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...
Python Brasil 2010 - Potter vs Voldemort - Lições ofidiglotas da prática Pyth...
 
Beating the (sh** out of the) GIL - Multithreading vs. Multiprocessing
Beating the (sh** out of the) GIL - Multithreading vs. MultiprocessingBeating the (sh** out of the) GIL - Multithreading vs. Multiprocessing
Beating the (sh** out of the) GIL - Multithreading vs. Multiprocessing
 
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...
 
Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System Administrators
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETL
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETLSimple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETL
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETL
 
Tales@tdc
Tales@tdcTales@tdc
Tales@tdc
 
A (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIA (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio API
 
閒聊Python應用在game server的開發
閒聊Python應用在game server的開發閒聊Python應用在game server的開發
閒聊Python應用在game server的開發
 

Viewers also liked

WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsWAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsDavid Beazley (Dabeaz LLC)
 
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...David Beazley (Dabeaz LLC)
 
Ctypes в игровых приложениях на python
Ctypes в игровых приложениях на pythonCtypes в игровых приложениях на python
Ctypes в игровых приложениях на pythonPyNSK
 
A Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyA Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyDavid Beazley (Dabeaz LLC)
 
Подключение внешних библиотек в python
Подключение внешних библиотек в pythonПодключение внешних библиотек в python
Подключение внешних библиотек в pythonMaxim Shalamov
 

Viewers also liked (6)

Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsWAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
 
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...
 
Ctypes в игровых приложениях на python
Ctypes в игровых приложениях на pythonCtypes в игровых приложениях на python
Ctypes в игровых приложениях на python
 
A Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyA Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and Concurrency
 
Подключение внешних библиотек в python
Подключение внешних библиотек в pythonПодключение внешних библиотек в python
Подключение внешних библиотек в python
 

Similar to Perl-C/C++ Integration with Swig

C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 
Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Jeffrey Clark
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Robert Lemke
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3Robert Lemke
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Robert Lemke
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Altece
 
designpatterns_blair_upe.ppt
designpatterns_blair_upe.pptdesignpatterns_blair_upe.ppt
designpatterns_blair_upe.pptbanti43
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIYoni Davidson
 

Similar to Perl-C/C++ Integration with Swig (20)

Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C++primer
C++primerC++primer
C++primer
 
Gcrc talk
Gcrc talkGcrc talk
Gcrc talk
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Lecture02
Lecture02Lecture02
Lecture02
 
designpatterns_blair_upe.ppt
designpatterns_blair_upe.pptdesignpatterns_blair_upe.ppt
designpatterns_blair_upe.ppt
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
C language
C languageC language
C language
 

Recently uploaded

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Perl-C/C++ Integration with Swig

  • 1. Perl-C/C++ Integration with Swig Dave Beazley Department of Computer Science University of Chicago Chicago, IL 60637 beazley@cs.uchicago.edu August 23, 1999 O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 2. Roadmap What is Swig? How does it work? Why would you want to use it? Advanced features. Limitations and rough spots. Future plans. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 3. What is Swig? It’s a compiler for connecting C/C++ with interpreters General idea: • Take a C program or library • Grab its external interface (e.g., a header file). • Feed to Swig. • Compile into an extension module. • Run from Perl (or Python, Tcl, etc...) • Life is good. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 4. Swig, h2xs and xsubpp Perl already has extension building tools • xsubpp • h2xs • Makemaker • Primarily used for extension building and distribution. Why use Swig? • Much less internals oriented. • General purpose (also supports Python, Tcl, etc...) • Better support for structures, classes, pointers, etc... Also... • Target audience is primarily C/C++ programmers. • Not Perl extension writers (well, not really). O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 5. How does it work? Typical C program Header file main() extern int foo(int n); extern double bar; Functions struct Person { Variables char *name; Objects char *email; }; Interesting C Program Swig Interface Perl %module myprog Swig %{ Wrappers #include "myprog.h" %} Functions extern int foo(int n); Variables extern double bar; Objects struct Person { char *name; char *email; }; O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 6. Swig Output Swig converts interface files into C wrapper code • Similar to the output of xsubpp. • It’s nasty and shouldn’t be looked at. Compilation steps: • Run Swig • Compile the wrapper code. • Link wrappers and original code into a shared library. • Cross fingers. If successful... • Program loads as a Perl extension. • Can access C/C++ from Perl. • With few (if any) changes to the C/C++ code (hopefully) O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 7. Example C Code Perl int foo(int, int); $r = foo(2,3); double Global; $Global = 3.14; #define BAR 5.5 print $BAR; ... ... Perl becomes an extension of the underlying C/C++ code • Can invoke functions. • Modify global variables. • Access constants. Almost anything that can be done in C can be done from Perl • We’ll get to limitations a little later. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 8. Interface Files Annotated Header Files Module name %module myprog Preamble %{ • Inclusion of header files #include "myprog.h" • Support code %} • Same idea as in yacc/bison Public Declarations extern int foo(int n); • Put anything you want in Perl here extern double bar; • Converted into wrappers. struct Person { • Usually a subset of a header file. char *name; char *email; Note : Can use header files }; • May need conditional compilation. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 9. Supported C/C++ Features Functions, variables, and constants • Functions accessed as Perl functions. • Global variables mapped into magic Perl variables. • Constants mapped into read-only variables. All C/C++ datatypes supported except: • Pointers to functions and pointers to arrays (can fix with a typedef). • long long and long double • Variable length arguments. • Bit-fields (can fix with slight modifications in interface file). • Pointers to members. Structures and classes • Access to members supported through accessor functions. • Can wrap into Perl "classes." • Inheritance (including multiple inheritance). • Virtual and static members. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 10. Pointers Swig allows arbitrary C pointers to be used • Turned into blessed references Pointers are opaque • Can freely manipulate from Perl. • But can’t peer inside. Type-checking • Pointers encoded with a type to perform run-time checks. • Better than just casting everything to void * or int. Works very well with C programs • Structures, classes, arrays, etc... • Besides, you can never have too many pointers... O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 11. Shadow Classes Structures and classes can be hidden behind a Perl class: C/C++ struct or class C accessor functions class Foo { Foo *new_Foo(); public: void delete_Foo(Foo *f); int x; int Foo_x_get(Foo *f); Foo(); int Foo_x_set(Foo *f, int x); ~Foo(); int Foo_bar(Foo *f, int); int bar(int); ... ... } Perl wrappers Use from a Perl script package Foo; $f = new Foo; sub new { $f->bar(3); return new_Foo(); $f->bar{’x’} = 7; } del $f; sub DESTROY { delete_Foo(); } ...etc... O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 12. Swig Applications User interfaces • Use Perl, Python, or Tcl as the interface to a C program. • This is particularly useful in certain applications. Rapid prototyping and debugging of C/C++ • Use scripts for testing. • Prototype new features. Systems integration • Use Perl, Python, or Tcl as a glue language. • Combine C libraries as extension modules. The key point: • Swig can greatly simplify these tasks. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 13. Interface Building Problems Swig attempts to be completely automated. • "Wrap it and forget it" Problem : C/C++ code varies widely (and may be a mess) • Pointer ambiguity (arrays, output values, etc...). • Preprocessor macros. • Error handling (exceptions, etc...) • Advanced C++ (templates, overloading, etc...) Other problems • A direct translation of a header file may not work well. • Swig only understands a subset of C. • May want to interface with Perl data structures. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 14. Parsing Problems Swig doesn’t understand certain declarations • Can remove with conditional compilation or comments Example: int foo(char *fmt, ...); // int foo(char *fmt, ...); int bar(int (*func)(int)); #ifndef SWIG int bar(int (*func)(int)); #define Width(im) (im->width) #endif int Width(Image *im); A Swig interface doesn’t need to match the C code. • Can cut out unneeded parts. • Play games with typedef and macros. • Write helper functions. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 15. Advanced Features Typemaps • A technique for modifying Swig’s type handling. Exception Handling • Converting C/C++ errors into Perl errors. Class and structure extension • Adding new methods to structures and classes • Building O-O interfaces to C programs. This is going to be a whirlwind tour... O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 16. Typemap Example Problem : Output values void getsize(Image *im, int *w, int *h) { *w = im->width; *h = im->height; } Solution: Typemap library %include typemaps.i %apply int *OUTPUT { int *w, int *h }; ... void getsize(Image *im, int *w, int *h); From Perl: ($w,$h) = getsize($im); Note: There is a lot of underlying magic here (see docs). O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 17. Exception Handling Problem : Converting C errors into Perl errors int foo() { ... throw Error; ... }; Solution (place in an interface file): %except(perl5) { $function if (Error) { croak("You blew it!"); } } Exception code gets inserted into all of the wrappers. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 18. Class Extension An interesting hack to attach methods to structs/classes typedef struct { int width; int height; ... } Image; $im = new Image; %addmethods Image { $im->plot(30,40,1); Image(int w, int h) { return CreateImage(w,h); print $im->{’width’}; } etc ... ~Image() { free(self); } void plot(int x, int y, int c) { ImagePlot(self,x,y,z); } ... } O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 19. Limitations Parsing capability is limited • Some types don’t work: int (*func[10])(int, double); int *const a; int **&a; • No macro expansion (Swig1.1) • A number of advanced C++ features not supported. Not all C/C++ code is easily scriptable • Excessive complexity. • Abuse of macros and templates. Better integration with Perl • Support for MakeMaker and other tools. • Windows is still a bit of a mess. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 20. Future Plans Swig1.1 is maintained, but is not the focus of development • Daily maintenance builds at http://swig.cs.uchicago.edu/SWIG Swig2.0 • A major rewrite and reorganization of Swig. • Primary goal is to make Swig more extensible. Highlights • Better parsing (new type system, preprocessing, etc...) • Plugable components (code generators, parsers, etc...) • Substantially improved code generation. • Release date : TBA. O’Reilly Open Source Conference 3 0 - Swig - August 23 1999
  • 21. Availability Swig is free. • www.swig.org (Primary) • swig.cs.uchicago.edu (Development) • CPAN Compatibility • Most versions of Perl (may need latest Swig however). • Unix, Windows. Acknowledgments • David Fletcher, Dominique Dumont, and Gary Holt. • Swig users who have contributed patches. • University of Utah • Los Alamos National Laboratory O’Reilly Open Source Conference 3 0 - Swig - August 23 1999