SlideShare a Scribd company logo
1 of 35
Download to read offline
EASY NATIVE WRAPPERS WITH 
SWIG 
2014 Barcelona Perl Workshop
Text 
Every time you open a pipe to a program to do something 
that Perl already knows how to do, God kills a kitten. 
- @pplu_io 
! 
Check CPAN to save kittens.
Going Native 
Obscure/Propietary libraries 
Legacy code 
Code Optimization* 
Test harness 
Glue
XS
XS is an interface description file format 
used to create an extension interface 
between Perl and C code (or a C library) 
which one wishes to use with Perl. 
-perlxs 1:1
“Hooking Perl to C using XS requires you to write a 
shell.pm module to bootstrap an object file that has 
been compiled from C code, which was in turn 
generated by xsubpp from a.xs source file 
containing pseudo-C annotated with an XS interface 
description.” 
–Brian D. Foy, “Perl Best Practices”
“Hooking Perl to C using XS requires you 
to write a shell.pm module 
to bootstrap an object file 
that has been compiled from C code, 
which was in turn 
generated by xsubpp 
from a.xs source file 
containing pseudo-C 
annotated with an XS interface description.” 
–Brian D. Foy, “Perl Best Practices”
“If that sounds horribly complicated, 
then you have achieved an accurate 
understanding of the use of xsubpp.” 
–Brian D. Foy, “Perl Best Practices”
Inline::C 
It’s C, but Inline!
Inline::C 
#!/usr/bin/env perl 
use strict; 
use Inline C => << 'END_C'; 
void hello() { 
printf("Hello, world!"); 
} 
END_C 
! 
hello();
How does it work?
Live demo
SWIG 
Simplified 
Wrapper and 
Interface 
Generator
“SWIG is an interface compiler that connects 
programs written in C and C++ with scripting 
languages such as Perl, Python, Ruby, and Tcl.” 
– http://www.swig.org/exec.html
Purpose 
Prototyping & Debugging 
Systems Integration 
Build extension modules
SWIG 
Open Source (GPL) 
Created in 1995 by Dave Beazley 
Support for a couple dozen languages by 2014 
http://www.swig.org/
Supported Languages 
Tcl 
Python 
Perl 
Java 
Ruby 
PHP 
Ocaml 
Pike 
C# 
Scheme 
Modula-3 
Lua 
Common Lisp 
R 
Octave 
Go 
D 
Javascript 
http://www.swig.org/compat.html#SupportedLanguages
Interface definition 
/* File : example.i */ 
! 
%module example 
! 
%inline %{ 
extern int gcd(int x, int y); 
extern double Foo; 
%}
C file 
/* File : example.c */ 
! 
/* A global variable */ 
double Foo = 3.0; 
! 
/* Compute the greatest common divisor of positive 
integers */ 
int gcd(int x, int y) { 
int g; 
g = y; 
while (x > 0) { 
g = x; 
x = y % x; 
y = g; 
} 
return g; 
}
Build Wrapper 
swig -perl example.i
Compile & Link (Ideal) 
cc -c example_wrap.c 
! 
cc -c example.c 
! 
ldd example_wrap.o example.o -o 
example.so
Compile & Link (Real World) 
cc -c -fno-common -DPERL_DARWIN -fno-strict-aliasing - 
pipe -fstack-protector -I/usr/local/include -I/opt/ 
local/include -I/Users/arturo/perl5/perlbrew/perls/ 
perl-5.10.1/lib/5.10.1//darwin-2level/CORE/ 
example_wrap.c 
! 
cc -c -fno-common -DPERL_DARWIN -fno-strict-aliasing - 
pipe -fstack-protector -I/usr/local/include -I/opt/ 
local/include -I/Users/arturo/perl5/perlbrew/perls/ 
perl-5.10.1/lib/5.10.1//darwin-2level/CORE/ example.c 
! 
env MACOSX_DEPLOYMENT_TARGET=10.3 cc -bundle - 
undefined dynamic_lookup -L/usr/local/lib -L/opt/ 
local/lib -fstack-protector example_wrap.o example.o 
-o example.bundle
Hello, SWIG! 
perl runme.pl 
The gcd of 42 and 105 is 21 
Foo = 3 
Foo = 3.1415926
Getting There 
Simpler interface file 
Add SWIG to build chain
(#|%)include 
%module MyModule 
%{ 
#include "mymodule.h" 
%} 
! 
%include "mymodule.h"
Makefile.PL 
use 5.008000; 
use Config; 
use ExtUtils::MakeMaker; 
use vars qw($version); 
$version='0.1'; 
my $cmd = qq{swig -outdir lib -o Fact_wrap.c -perl Fact.i}; 
print "Executing $cmdn"; 
system($cmd); 
if($?==-1) { 
die("failed to execute: $!"); 
} elsif($?>0) { 
die("Error creating perl wrapper: $?"); 
} 
WriteMakefile( 
NAME => 'Fact', 
VERSION => $version, 
PREREQ_PM => {}, 
DEFINE => '-DMACOSX '.$Config{ccflags}, 
INC => '', 
OBJECT => '$(O_FILES)', 
clean => { 
FILES => 'lib/Fact.pm Fact_wrap.c', 
}, 
PMLIBDIRS => [ 'lib', 'lib/Fact' ], 
);
Live demo!
structs 
struct Vector { 
double x,y; 
}; 
package Vect::Vector; 
use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); 
@ISA = qw( Vect ); 
%OWNER = (); 
%ITERATORS = (); 
*swig_x_get = *Vectc::Vector_x_get; 
*swig_x_set = *Vectc::Vector_x_set; 
*swig_y_get = *Vectc::Vector_y_get; 
*swig_y_set = *Vectc::Vector_y_set; 
…
Sane Accessors 
my $v = Vect::Vector->new(); 
$v->{x}=3; 
$v->{y}=4;
Distribute on CPAN 
No need to force swig dependency 
Include the generated wrapper (*_wrap.c, *.pm) 
Include the interface definition as a courtesy
Tip of the Iceberg 
C++ 
Exceptions 
Typemaps 
%perlcode
++$learn 
http://www.slideshare.net/daoswald/getting-started-with- 
perl-xs-and-inlinec 
Cozens, Simon. “Advanced Perl Programming” 
Orwant, Jon. “Computer Science & Perl Programming” 
http://www.swig.org/
Q&A
Thank you! 
@codehead 
javier@rodriguez.org.mx 
scribd.com/javierrgz

More Related Content

What's hot

Take advantage of C++ from Python
Take advantage of C++ from PythonTake advantage of C++ from Python
Take advantage of C++ from PythonYung-Yu Chen
 
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...PyData
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Yung-Yu Chen
 
Boost.Python - domesticating the snake
Boost.Python - domesticating the snakeBoost.Python - domesticating the snake
Boost.Python - domesticating the snakeSławomir Zborowski
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.Mosky Liu
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimeNational Cheng Kung University
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to ClimeMosky Liu
 
Python on a chip
Python on a chipPython on a chip
Python on a chipstoggi
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopPyCon Italia
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Max Kleiner
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APIMr. Vengineer
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
Async await in C++
Async await in C++Async await in C++
Async await in C++cppfrug
 
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingПро асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingPython Meetup
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 

What's hot (20)

Take advantage of C++ from Python
Take advantage of C++ from PythonTake advantage of C++ from Python
Take advantage of C++ from Python
 
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
Mixed-language Python/C++ debugging with Python Tools for Visual Studio- Pave...
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020
 
Boost.Python - domesticating the snake
Boost.Python - domesticating the snakeBoost.Python - domesticating the snake
Boost.Python - domesticating the snake
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to Clime
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntop
 
Perl-C/C++ Integration with Swig
Perl-C/C++ Integration with SwigPerl-C/C++ Integration with Swig
Perl-C/C++ Integration with Swig
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
FTD JVM Internals
FTD JVM InternalsFTD JVM Internals
FTD JVM Internals
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
 
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingПро асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer Wargaming
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 

Similar to Easy native wrappers with SWIG

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfThninh2
 
Software Development Automation With Scripting Languages
Software Development Automation With Scripting LanguagesSoftware Development Automation With Scripting Languages
Software Development Automation With Scripting LanguagesIonela
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionProf. Wim Van Criekinge
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014biicode
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckrICh morrow
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?lichtkind
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
 
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-FormatsBig Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-FormatsGuido Schmutz
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshopjulien pauli
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With YouDalibor Gogic
 
NginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesClaudio Borges
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureMichaël Lopez
 
Power shell training
Power shell trainingPower shell training
Power shell trainingDavid Brabant
 
Holy PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionHoly PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionDave Diehl
 

Similar to Easy native wrappers with SWIG (20)

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Dynamic Web Programming
Dynamic Web ProgrammingDynamic Web Programming
Dynamic Web Programming
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
 
Software Development Automation With Scripting Languages
Software Development Automation With Scripting LanguagesSoftware Development Automation With Scripting Languages
Software Development Automation With Scripting Languages
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Serverless in action
Serverless in actionServerless in action
Serverless in action
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-FormatsBig Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshop
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
NginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniques
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructure
 
Power shell training
Power shell trainingPower shell training
Power shell training
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Holy PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood editionHoly PowerShell, BATman! - dogfood edition
Holy PowerShell, BATman! - dogfood edition
 

More from Javier Arturo Rodríguez

More from Javier Arturo Rodríguez (9)

Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
 
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
 
WordPress Performance Tuning
WordPress Performance TuningWordPress Performance Tuning
WordPress Performance Tuning
 
WordPress for SysAdmins
WordPress for SysAdminsWordPress for SysAdmins
WordPress for SysAdmins
 
Open Data: a view from the trenches
Open Data: a view from the trenchesOpen Data: a view from the trenches
Open Data: a view from the trenches
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Build an autoversioning filesystem with Apache2
Build an autoversioning filesystem with Apache2Build an autoversioning filesystem with Apache2
Build an autoversioning filesystem with Apache2
 
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
 
DatosEnCrudo.org
DatosEnCrudo.orgDatosEnCrudo.org
DatosEnCrudo.org
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Recently uploaded (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Easy native wrappers with SWIG

  • 1. EASY NATIVE WRAPPERS WITH SWIG 2014 Barcelona Perl Workshop
  • 2. Text Every time you open a pipe to a program to do something that Perl already knows how to do, God kills a kitten. - @pplu_io ! Check CPAN to save kittens.
  • 3.
  • 4. Going Native Obscure/Propietary libraries Legacy code Code Optimization* Test harness Glue
  • 5. XS
  • 6. XS is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. -perlxs 1:1
  • 7. “Hooking Perl to C using XS requires you to write a shell.pm module to bootstrap an object file that has been compiled from C code, which was in turn generated by xsubpp from a.xs source file containing pseudo-C annotated with an XS interface description.” –Brian D. Foy, “Perl Best Practices”
  • 8. “Hooking Perl to C using XS requires you to write a shell.pm module to bootstrap an object file that has been compiled from C code, which was in turn generated by xsubpp from a.xs source file containing pseudo-C annotated with an XS interface description.” –Brian D. Foy, “Perl Best Practices”
  • 9. “If that sounds horribly complicated, then you have achieved an accurate understanding of the use of xsubpp.” –Brian D. Foy, “Perl Best Practices”
  • 10. Inline::C It’s C, but Inline!
  • 11. Inline::C #!/usr/bin/env perl use strict; use Inline C => << 'END_C'; void hello() { printf("Hello, world!"); } END_C ! hello();
  • 12. How does it work?
  • 14. SWIG Simplified Wrapper and Interface Generator
  • 15. “SWIG is an interface compiler that connects programs written in C and C++ with scripting languages such as Perl, Python, Ruby, and Tcl.” – http://www.swig.org/exec.html
  • 16. Purpose Prototyping & Debugging Systems Integration Build extension modules
  • 17. SWIG Open Source (GPL) Created in 1995 by Dave Beazley Support for a couple dozen languages by 2014 http://www.swig.org/
  • 18. Supported Languages Tcl Python Perl Java Ruby PHP Ocaml Pike C# Scheme Modula-3 Lua Common Lisp R Octave Go D Javascript http://www.swig.org/compat.html#SupportedLanguages
  • 19. Interface definition /* File : example.i */ ! %module example ! %inline %{ extern int gcd(int x, int y); extern double Foo; %}
  • 20. C file /* File : example.c */ ! /* A global variable */ double Foo = 3.0; ! /* Compute the greatest common divisor of positive integers */ int gcd(int x, int y) { int g; g = y; while (x > 0) { g = x; x = y % x; y = g; } return g; }
  • 21. Build Wrapper swig -perl example.i
  • 22. Compile & Link (Ideal) cc -c example_wrap.c ! cc -c example.c ! ldd example_wrap.o example.o -o example.so
  • 23. Compile & Link (Real World) cc -c -fno-common -DPERL_DARWIN -fno-strict-aliasing - pipe -fstack-protector -I/usr/local/include -I/opt/ local/include -I/Users/arturo/perl5/perlbrew/perls/ perl-5.10.1/lib/5.10.1//darwin-2level/CORE/ example_wrap.c ! cc -c -fno-common -DPERL_DARWIN -fno-strict-aliasing - pipe -fstack-protector -I/usr/local/include -I/opt/ local/include -I/Users/arturo/perl5/perlbrew/perls/ perl-5.10.1/lib/5.10.1//darwin-2level/CORE/ example.c ! env MACOSX_DEPLOYMENT_TARGET=10.3 cc -bundle - undefined dynamic_lookup -L/usr/local/lib -L/opt/ local/lib -fstack-protector example_wrap.o example.o -o example.bundle
  • 24. Hello, SWIG! perl runme.pl The gcd of 42 and 105 is 21 Foo = 3 Foo = 3.1415926
  • 25. Getting There Simpler interface file Add SWIG to build chain
  • 26. (#|%)include %module MyModule %{ #include "mymodule.h" %} ! %include "mymodule.h"
  • 27. Makefile.PL use 5.008000; use Config; use ExtUtils::MakeMaker; use vars qw($version); $version='0.1'; my $cmd = qq{swig -outdir lib -o Fact_wrap.c -perl Fact.i}; print "Executing $cmdn"; system($cmd); if($?==-1) { die("failed to execute: $!"); } elsif($?>0) { die("Error creating perl wrapper: $?"); } WriteMakefile( NAME => 'Fact', VERSION => $version, PREREQ_PM => {}, DEFINE => '-DMACOSX '.$Config{ccflags}, INC => '', OBJECT => '$(O_FILES)', clean => { FILES => 'lib/Fact.pm Fact_wrap.c', }, PMLIBDIRS => [ 'lib', 'lib/Fact' ], );
  • 29. structs struct Vector { double x,y; }; package Vect::Vector; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( Vect ); %OWNER = (); %ITERATORS = (); *swig_x_get = *Vectc::Vector_x_get; *swig_x_set = *Vectc::Vector_x_set; *swig_y_get = *Vectc::Vector_y_get; *swig_y_set = *Vectc::Vector_y_set; …
  • 30. Sane Accessors my $v = Vect::Vector->new(); $v->{x}=3; $v->{y}=4;
  • 31. Distribute on CPAN No need to force swig dependency Include the generated wrapper (*_wrap.c, *.pm) Include the interface definition as a courtesy
  • 32. Tip of the Iceberg C++ Exceptions Typemaps %perlcode
  • 33. ++$learn http://www.slideshare.net/daoswald/getting-started-with- perl-xs-and-inlinec Cozens, Simon. “Advanced Perl Programming” Orwant, Jon. “Computer Science & Perl Programming” http://www.swig.org/
  • 34. Q&A
  • 35. Thank you! @codehead javier@rodriguez.org.mx scribd.com/javierrgz