SlideShare a Scribd company logo
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.0
David Beazley (Dabeaz LLC)
 
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)
David Beazley (Dabeaz LLC)
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
David Beazley (Dabeaz LLC)
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
David 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 Lock
David Beazley (Dabeaz LLC)
 
Python Generator Hacking
Python Generator HackingPython Generator Hacking
Python Generator Hacking
David 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 II
David Beazley (Dabeaz LLC)
 
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
David Beazley (Dabeaz LLC)
 
PyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialPyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 Tutorial
Justin Lin
 
Ry pyconjp2015 karaoke
Ry pyconjp2015 karaokeRy pyconjp2015 karaoke
Ry pyconjp2015 karaoke
Renyuan 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. Multiprocessing
Guy 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 Administrators
Roberto Polli
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
Charles-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 ETL
Romain 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 API
Edward 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

Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
 
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
David 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 в игровых приложениях на python
PyNSK
 
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
David Beazley (Dabeaz LLC)
 
Подключение внешних библиотек в python
Подключение внешних библиотек в pythonПодключение внешних библиотек в python
Подключение внешних библиотек в python
Maxim 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

Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
C++primer
C++primerC++primer
C++primer
leonlongli
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
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 FLOW3
Robert Lemke
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
Robert Lemke
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
aptechsravan
 
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
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
designpatterns_blair_upe.ppt
designpatterns_blair_upe.pptdesignpatterns_blair_upe.ppt
designpatterns_blair_upe.ppt
banti43
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
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
Kevlin 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 Maloth
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
Yoni Davidson
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
C language
C languageC language
C language
Mukul Kirti Verma
 

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

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 

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