SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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的開發
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Último

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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 WorkerThousandEyes
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 

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