Easy Native Wrappers With SWIG
Easy Native Wrappers With SWIG
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
Going Native
Obscure/Propietary libraries
Legacy code
Code Optimization*
Test harness
Glue
XS
Inline::C
Inline::C
#!/usr/bin/env perl
use strict;
use Inline C => << 'END_C';
void hello() {
printf("Hello, world!");
}
END_C
!
hello();
Live demo
SWIG
Simplified
Wrapper and
Interface
Generator
Purpose
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
Ocaml
Common Lisp
Python
Pike
Perl
C#
Octave
Java
Scheme
Go
Ruby
Modula-3
PHP
Lua
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
cc -c example.c
!
-o
Hello, SWIG!
perl runme.pl
The gcd of 42 and 105 is 21
Foo = 3
Foo = 3.1415926
Getting There
(#|%)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 $cmd\n";
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
++$learn
http://www.slideshare.net/daoswald/getting-startedwith-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