SlideShare a Scribd company logo
1 of 22
Python with a of C++
Bob McNaughton
PyData NYC 2015
• Simplified Wrapper and Interface Generator
• Allow the use of C/C++ from other languages
• http://swig.org/
• Originally developed by Dave Beazly
• First released in February 1996
• Latest release 3.0.7, August 3rd, 2015
• Actively maintained, several releases a year
What is SWIG?
What other languages?
$ swig -help
Target Language Options
-allegrocl - Generate ALLEGROCL wrappers
-chicken - Generate CHICKEN wrappers
-clisp - Generate CLISP wrappers
-cffi - Generate CFFI wrappers
-csharp - Generate C# wrappers
-guile - Generate Guile wrappers
-java - Generate Java wrappers
-lua - Generate Lua wrappers
-modula3 - Generate Modula 3 wrappers
-mzscheme - Generate Mzscheme wrappers
-ocaml - Generate Ocaml wrappers
-perl - Generate Perl wrappers
-php - Generate PHP wrappers
-pike - Generate Pike wrappers
-python - Generate Python wrappers
-ruby - Generate Ruby wrappers
-sexp - Generate Lisp S-Expressions wrappers
-tcl - Generate Tcl wrappers
-uffi - Generate Common Lisp / UFFI wrappers
-xml - Generate XML wrappers
Are there any alternatives?
• Cython
• cTypes
• Cpython C API
Why would you ever want to call C/C++ from Python?
• Speed
• Existing C/C++ libraries
• With or without source
• Develop faster initially with Python
• Speed up parts that the profiler shows as critical
C++ Fibonacci
if (n < 0)
nextTerm = -1;
else if (n == 0)
nextTerm = 0;
else if (n == 1)
nextTerm = 1;
else {
firstTerm = 0;
secondTerm = 1;
for (int i = 0; i < n-1; ++i) {
nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
Python Fibonacci
def fib(n):
if (n < 0):
return -1
elif (n == 0):
return 0
elif (n == 1):
return 1
else:
a,b = 0,1
for i in range(n-1):
a,b = b,a+b
return a
How do they compare?
• Had to run both multiple times to get something measurable
• C++ significantly faster
• Python doesn’t overflow
C++ Library routine
long long fib(int n)
{
long long firstTerm = 0, secondTerm = 1, nextTerm;
if (n < 0)
return -1;
if (n == 0)
return 0;
if (n == 1)
return 1;
for (int i = 1; i < n-1; ++i) {
nextTerm = firstTerm + secondTerm;
if (nextTerm < secondTerm) // Overflow!
return -1;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
return nextTerm;
}
C++ Header File
long long fib(int n);
Make a shared object or dll
g++ -g –c –o fibl.o fibl.cpp
g++ -g –shared –fPIC –Wl,-soname,libfib.so –o libfib.so fibl.o
Use this .so from C++
#include <iostream>
#include <stdlib.h>
#include "fib.h"
using namespace std;
int main(int argc, char* argv[]) {
if (argc < 2)
{
cout << "Usage: " << argv[0] << " <fibonacci number to print>" << endl;
return -1;
}
long n = strtol(argv[1], NULL, 10);
for (int i=0; i<100000; i++) {
fib(n);
}
cout << "Fibonacci Number " << n << " is " << fib(n) << endl;
return 0;
}
Compile with:
g++ -g –L. –lfib –o fibm fibm.cpp
How does it compare to no .so?
Slightly slower
Still overflows
Now call the same .so from Python
SWIG interface file, fibl.i
%module fibl
%{
#include "fib.h"
%}
%include "fib.h"
Run SWIG on the interface file
swig –python fibl.i
Produces fibl_wrap.c and fibl.py
Turn the SWIG outputs into a .so
g++ -g –fpic –c fibl_wrap.c –I /usr/include/python3.5m
g++ -g –shared –L. –lfib fibl_wrap.o –o _fibl.so
$ ldd _fibl.so
linux-vdso.so.1 (0x00007ffdd6d9e000)
libfib.so => ./libfib.so (0x00007fcbdc07e000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007fcbdbcc9000)
libm.so.6 => /usr/lib/libm.so.6 (0x00007fcbdb9cb000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007fcbdb7b4000)
libc.so.6 => /usr/lib/libc.so.6 (0x00007fcbdb410000)
/usr/lib64/ld-linux-x86-64.so.2 (0x000055f6c1f6c000)
Now call the .so from Python
import sys
import fibl
x=int(sys.argv[1])
for i in range (1, 100000):
fibl.fib(x)
print("Fibonacci number", x, "is", fibl.fib(x))
Now how do the results compare?
C++ still faster, but it is much closer now
Python now overflows
What about a more complicated example?
#include <rw/sortvec.h>
#include <rw/collstr.h>
int main ()
{
RWSortedVector sv;
sv.insert(new RWCollectableString("dog"));
sv.insert(new RWCollectableString("cat"));
sv.insert(new RWCollectableString("fish"));
RWSortedVectorIterator next(sv);
RWCollectableString* item;
while( (item = (RWCollectableString*)next() ) != 0)
std::cout << *item << std::endl;
sv.clearAndDestroy();
return 0;
}
Try the obvious SWIG interface file
%module fibl
%{
#include <rw/sortvec.h>
#include <rw/collstr.h>
%}
%include <rw/sortvec.h>
%include <rw/collstr.h>
Conclusion
• Works fine for C
• C++ can be a problem.
• The only option if all you have is a header file and a dynamic library

More Related Content

What's hot

Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performancesource{d}
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with GoDigium
 
Parallel Computing Example with Raspberry Pi Cluster
Parallel Computing Example with Raspberry Pi ClusterParallel Computing Example with Raspberry Pi Cluster
Parallel Computing Example with Raspberry Pi ClusterHerpiko Dwi Aguno
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torchRiza Fahmi
 
Código para Latch físico: Touch_calibrate.py
Código para Latch físico: Touch_calibrate.pyCódigo para Latch físico: Touch_calibrate.py
Código para Latch físico: Touch_calibrate.pyChema Alonso
 
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+Romain Dorgueil
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminarygo-lang
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2Bahul Neel Upadhyaya
 
How to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterHow to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterYoshifumi Kawai
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)Subhas Kumar Ghosh
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Maarten Mulders
 
Why is a[1] fast than a.get(1)
Why is a[1]  fast than a.get(1)Why is a[1]  fast than a.get(1)
Why is a[1] fast than a.get(1)kao kuo-tung
 
Custard pi 7 user information
Custard pi 7 user informationCustard pi 7 user information
Custard pi 7 user informationSeggy Segaran
 

What's hot (20)

Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with Go
 
Parallel Computing Example with Raspberry Pi Cluster
Parallel Computing Example with Raspberry Pi ClusterParallel Computing Example with Raspberry Pi Cluster
Parallel Computing Example with Raspberry Pi Cluster
 
PyHEP 2019: Python 3.8
PyHEP 2019: Python 3.8PyHEP 2019: Python 3.8
PyHEP 2019: Python 3.8
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torch
 
Código para Latch físico: Touch_calibrate.py
Código para Latch físico: Touch_calibrate.pyCódigo para Latch físico: Touch_calibrate.py
Código para Latch físico: Touch_calibrate.py
 
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2
 
Scapy
ScapyScapy
Scapy
 
How to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterHow to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatter
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Concurrency in Python4k
Concurrency in Python4kConcurrency in Python4k
Concurrency in Python4k
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)
 
Why is a[1] fast than a.get(1)
Why is a[1]  fast than a.get(1)Why is a[1]  fast than a.get(1)
Why is a[1] fast than a.get(1)
 
Custard pi 7 user information
Custard pi 7 user informationCustard pi 7 user information
Custard pi 7 user information
 

Similar to SWIG to Integrate C++ Libraries in Python

PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsHenry Schreiner
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPyDong-hee Na
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)Qiangning Hong
 
Numba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPyNumba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPyTravis Oliphant
 
GoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPHGoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPHGautam Rege
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOKris Findlay
 
PyHEP 2018: Tools to bind to Python
PyHEP 2018:  Tools to bind to PythonPyHEP 2018:  Tools to bind to Python
PyHEP 2018: Tools to bind to PythonHenry Schreiner
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Nikita Popov
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programmingMarc Gouw
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Romain Dorgueil
 
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilSimple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilPôle Systematic Paris-Region
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Henry Schreiner
 
Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成zhongbing liu
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelMark Rees
 
Lisandro dalcin-mpi4py
Lisandro dalcin-mpi4pyLisandro dalcin-mpi4py
Lisandro dalcin-mpi4pyA Jorge Garcia
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Samuel Lampa
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗Pofat Tseng
 

Similar to SWIG to Integrate C++ Libraries in Python (20)

PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
Numba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPyNumba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPy
 
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
 
mpi4py.pdf
mpi4py.pdfmpi4py.pdf
mpi4py.pdf
 
GoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPHGoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPH
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIO
 
PyHEP 2018: Tools to bind to Python
PyHEP 2018:  Tools to bind to PythonPyHEP 2018:  Tools to bind to Python
PyHEP 2018: Tools to bind to Python
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
 
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilSimple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
 
Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
 
Lisandro dalcin-mpi4py
Lisandro dalcin-mpi4pyLisandro dalcin-mpi4py
Lisandro dalcin-mpi4py
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 

Recently uploaded

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Recently uploaded (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

SWIG to Integrate C++ Libraries in Python

  • 1. Python with a of C++ Bob McNaughton PyData NYC 2015
  • 2. • Simplified Wrapper and Interface Generator • Allow the use of C/C++ from other languages • http://swig.org/ • Originally developed by Dave Beazly • First released in February 1996 • Latest release 3.0.7, August 3rd, 2015 • Actively maintained, several releases a year What is SWIG?
  • 3. What other languages? $ swig -help Target Language Options -allegrocl - Generate ALLEGROCL wrappers -chicken - Generate CHICKEN wrappers -clisp - Generate CLISP wrappers -cffi - Generate CFFI wrappers -csharp - Generate C# wrappers -guile - Generate Guile wrappers -java - Generate Java wrappers -lua - Generate Lua wrappers -modula3 - Generate Modula 3 wrappers -mzscheme - Generate Mzscheme wrappers -ocaml - Generate Ocaml wrappers -perl - Generate Perl wrappers -php - Generate PHP wrappers -pike - Generate Pike wrappers -python - Generate Python wrappers -ruby - Generate Ruby wrappers -sexp - Generate Lisp S-Expressions wrappers -tcl - Generate Tcl wrappers -uffi - Generate Common Lisp / UFFI wrappers -xml - Generate XML wrappers
  • 4. Are there any alternatives? • Cython • cTypes • Cpython C API
  • 5. Why would you ever want to call C/C++ from Python? • Speed • Existing C/C++ libraries • With or without source • Develop faster initially with Python • Speed up parts that the profiler shows as critical
  • 6. C++ Fibonacci if (n < 0) nextTerm = -1; else if (n == 0) nextTerm = 0; else if (n == 1) nextTerm = 1; else { firstTerm = 0; secondTerm = 1; for (int i = 0; i < n-1; ++i) { nextTerm = firstTerm + secondTerm; firstTerm = secondTerm; secondTerm = nextTerm; } }
  • 7. Python Fibonacci def fib(n): if (n < 0): return -1 elif (n == 0): return 0 elif (n == 1): return 1 else: a,b = 0,1 for i in range(n-1): a,b = b,a+b return a
  • 8. How do they compare? • Had to run both multiple times to get something measurable • C++ significantly faster • Python doesn’t overflow
  • 9. C++ Library routine long long fib(int n) { long long firstTerm = 0, secondTerm = 1, nextTerm; if (n < 0) return -1; if (n == 0) return 0; if (n == 1) return 1; for (int i = 1; i < n-1; ++i) { nextTerm = firstTerm + secondTerm; if (nextTerm < secondTerm) // Overflow! return -1; firstTerm = secondTerm; secondTerm = nextTerm; } return nextTerm; }
  • 10. C++ Header File long long fib(int n);
  • 11. Make a shared object or dll g++ -g –c –o fibl.o fibl.cpp g++ -g –shared –fPIC –Wl,-soname,libfib.so –o libfib.so fibl.o
  • 12. Use this .so from C++ #include <iostream> #include <stdlib.h> #include "fib.h" using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " <fibonacci number to print>" << endl; return -1; } long n = strtol(argv[1], NULL, 10); for (int i=0; i<100000; i++) { fib(n); } cout << "Fibonacci Number " << n << " is " << fib(n) << endl; return 0; }
  • 13. Compile with: g++ -g –L. –lfib –o fibm fibm.cpp
  • 14. How does it compare to no .so? Slightly slower Still overflows
  • 15. Now call the same .so from Python SWIG interface file, fibl.i %module fibl %{ #include "fib.h" %} %include "fib.h"
  • 16. Run SWIG on the interface file swig –python fibl.i Produces fibl_wrap.c and fibl.py
  • 17. Turn the SWIG outputs into a .so g++ -g –fpic –c fibl_wrap.c –I /usr/include/python3.5m g++ -g –shared –L. –lfib fibl_wrap.o –o _fibl.so $ ldd _fibl.so linux-vdso.so.1 (0x00007ffdd6d9e000) libfib.so => ./libfib.so (0x00007fcbdc07e000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007fcbdbcc9000) libm.so.6 => /usr/lib/libm.so.6 (0x00007fcbdb9cb000) libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007fcbdb7b4000) libc.so.6 => /usr/lib/libc.so.6 (0x00007fcbdb410000) /usr/lib64/ld-linux-x86-64.so.2 (0x000055f6c1f6c000)
  • 18. Now call the .so from Python import sys import fibl x=int(sys.argv[1]) for i in range (1, 100000): fibl.fib(x) print("Fibonacci number", x, "is", fibl.fib(x))
  • 19. Now how do the results compare? C++ still faster, but it is much closer now Python now overflows
  • 20. What about a more complicated example? #include <rw/sortvec.h> #include <rw/collstr.h> int main () { RWSortedVector sv; sv.insert(new RWCollectableString("dog")); sv.insert(new RWCollectableString("cat")); sv.insert(new RWCollectableString("fish")); RWSortedVectorIterator next(sv); RWCollectableString* item; while( (item = (RWCollectableString*)next() ) != 0) std::cout << *item << std::endl; sv.clearAndDestroy(); return 0; }
  • 21. Try the obvious SWIG interface file %module fibl %{ #include <rw/sortvec.h> #include <rw/collstr.h> %} %include <rw/sortvec.h> %include <rw/collstr.h>
  • 22. Conclusion • Works fine for C • C++ can be a problem. • The only option if all you have is a header file and a dynamic library