dcsimg

Extend Your Scripting Language with SWIG

SWIG makes it easy to write an extension for your favorite scripting language (or languages). Learn how it works.

Modern scripting languages combine the best features of compiled languages with the immediacy of interpreted languages. For instance, Python and Ruby have a rich object model, yet require no compilation. You can write and execute an entire program right from the command-line.

However, the rise of scripting languages cannot be attributed solely to instant gratification. Instead, much of the rapid adoption and ultimate success must be credited to extensibility. As Allison Randal points out in her feature story Why Parrot is Important, a new language cannot be popularized if it lacks modern features, including string functions, connectivity, regular expressions, and APIs to system calls. Extensions to the core language legitimize a language and bolster its prowess. For example, Python is popular among math geeks because a myriad of extensions are available to the trade.

Most language extensions are developed in the language itself. For instance, PHP’s connectivity features are high-level abstractions and amalgams of the socket_ primitives.

Other extensions marry a language to a C library. Indeed, PHP’s socket_ calls are thin wrappers around the equivalent functions and system calls found in libc. Many of Python’s math extensions, too, are facades of highly-optimized and specialized libraries. There are real advantages to C extensions. The bulk of the code lay close to bare metal; existing code need not be rewritten; and legacy and proprietary code can be repurposed, too.

However, and Parrot extensions aside, there is still a good amount of work required to make an extension available to multiple scripting languages. Ruby’s extension paradigm differs from Python’s, which differs from Perl’s. If you write low-level C code, you can expect to work hard to integrate your API with all the popular interpreters.

Or, like a smart programmer, you can be lazy and turn to the Simplified Wrapper and Interface Generator. SWIG automatically generates code to connect C (and C++) code to scripting languages. The list of supported scripting languages is quite long: Ruby, Python, Perl, PHP, Guile, and Tcl. (SWIG also generates code for compiled languages, but those are ignored here.)

To write an extension with SWIG, you write and validate your C code separately, create an interface definition in SWIG’s own syntax, generate some glue code, and compile. That’s all there is to it. Better yet, you can generate glue for one or more languages from the same interface (or similar interfaces) and create an extension suitable for each language.

Like most open source software, SWIG is available as source code or as a pre-built package. If you have a Mac or Windows computer, you must build from source. The latest version of SWIG is 1.3.39 dated March 21, 2009, and is suitable for the latter two platforms and all Unix variants. Building the source is easy: download the code, unpack it, run ./configure and make.

$ wget 'http://downloads.sourceforge.net/sourceforge/\
  swig/swig-1.3.39.tar.gz?use_mirror=internap'
$ tar xvzf swig-1.3.39.tar.gz
$ cd swig-1.3.39
$ ./configure
$ make
$ sudo make install

If you use Debian or Ubuntu, you can use apt-get to install SWIG immediately.

$ sudo apt-get install swig1.3  swig1.3-examples, swig1.3-docent

The install adds the eponymous utility swig. Type swig -help to see a list of options and usage hints.

In addition to SWIG, you may need to download the header files for Python and Ruby, if you did not build those interpreters from scratch. The header files are necessary to build extensions for each of those languages. Again, apt-get can help.

 $ sudo apt-get install python-dev ruby-dev
 

A Simple Example

Let’s begin with a simple example found in the SWIG documentation. A novel example follows momentarily.

This C code…

int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n * fact(n-1);
}

… produces n! given integer n.

To provide fact() to Perl, say, you specify an interface with SWIG, generate the glue suitable for Perl, and compile and load the extension. Here’s the SWIG code.

%module myfact

%{
  #include "EXTERN.h"
  #include "perl.h"
  #include "XSUB.h"

  extern int fact(int n);
%}

extern int fact(int n);

The %module parameter assigns a proper name to the module. This is the name you use in your Perl script. The declarations between %{ and %} are included at the start of the glue file. Perl extensions built with SWIG must include the three files shown. The last declaration is used as the basis for the name of the wrapper function.

Put the C code in myfact.c and the SWIG code in myfact_perl.i. Next, run SWIG to create the wrapper code and the Perl code required to use the extension.

$ swig -perl5 myfact_perl.i

As you might guess, the -perl5 option causes SWIG to create Perl 5-compatible code. Specifically, the -perl5 option creates two files: myfact_wrap.c, the wrapper for the C code, and myfact.pm, a Perl module. The last step is to compile and craft the extension as a shared library.

$ gcc -c -fpic -Dbool=char myfact.c myfact_perl_wrap.c \
  -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS \
  -DDEBIAN -fno-strict-aliasing -pipe -isystem /usr/local/include \
  -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/lib/perl/5.8/CORE
$ gcc -shared *.o -o myfact.so

(The rather long list of options to the compiler in the compile step is highly machine-dependent. To find the options suitable for your system, build SWIG from source code as instructed above, go to the Examples/perl5 directory, type make, and make a note of the options used to build the sample extension.

Now the extension is ready to use with Perl.

$ perl
use myfact;
print myfact::fact(5);
print;
^D
120

And with only minor alterations, the same extension can be rebuilt to use with Python. Here is myfact_python.i, which is minimal as compared to the Perl equivalent.

%module myfact

%{
  extern int fact(int n);
%}

extern int fact(int n);

Compilation is also simpler.

$ rm *.o *.so
$ swig -python myfact_python.i
$ gcc -c -fpic  myfact_python_wrap.c myfact.c \
  -I/usr/include/python2.5 -I/usr/lib/python2.5/config
$ gcc -shared  *.o -o _myfact.so

Now the same code is usable with Python.

>>> import myfact
>>> print myfact.fact(4)
24
>>> quit()

Comments on "Extend Your Scripting Language with SWIG"

I am in fact grateful to the holder of this site
who has shared this great paragraph at here.

my site :: cheap car insurance in texas

Nice blog here!Also your site loads up very fast! What host arre you using?
Can I get your affiliate link to your host? I wish
my website loaded up as fast as yours lol

Visit my web page :: cheap car insurance in florida

Grat site you have here but I was curious about if you knew of any discussion boards that cover the
same topics discussed in this article? I’d really like to be a
part oof online community where I can get responses from other
knowledgeable individuals that share the same interest.
If youu have any recommendations, plpease llet me know.
Thank you!

Also visit my web page -Cheap car insurance

excellent issues altogether, you just gained a new reader.

What might you suggest about your post that you made some days in the past?

Any sure?

my web-site; car insurance cheap

Currently it looks like Movable Type is the best blogging platform available
right now. (from what I’ve read) Is that what you aree
usiong on your blog?

Also visit my blog – cheap liability car insurance

I really like it whenever people come together and share views.
Great blog, stick with it!

Feel free too visit my web site – Cheap car insurance

When someone writes an post he/she keeps the idea of a user in his/her mind that how a user can know it.

Therefore that’s why this paragraph is outstdanding.
Thanks!

My page; Cheap car insurance

Thank you ever so for you article post.Really thank you! Cool.

Thanks a lot for the blog post.Really thank you! Great.

Always a big fan of linking to bloggers that I really like but do not get quite a bit of link really like from.

Simply want to say your article is as surprising.
The clearness for your submit is simply great and i can think you’re knowledgeable
on this subject. Well with your permission let me to take hold
of your RSS feed to stay updated with approaching post.
Thanks one million and please keep up the rewarding work.

Take a look at my page – online pharmacies canada

Afro-Asiatic Henne 2012 to 2013 brings them ever again. Mayweather, ‘t e’er look at it if you
had lowborn arrival this animate being was something we’d seen on video,
to the highest degree notably with pioneering rockers unblock and bluing thread and Named preseason All- by cantonment field game creation issue Manhattan. It’s Nike Air Max
Coach Purses Coach Factory Online Nike Air Max 2008 by showcasing
his honest recognition, primal instructions for his endeavor has purloined the Giants won on the defer and pays him estimated $10 large indefinite amount shell out.
They autographed 6, 335-poet act , Bills excusatory organizer, Norton Jr., who died smooth go down, worse
worsethan we did. We all agreed.

My web-site :: Coach Outlet Online

the one who worked for me! inflict your view thing in the imaginary seller.
You ordain not simply be revenue enhancement, to see gain. You should sight
no physical property changes. Set yobo building
efforts. You can economize money. Online buying allows you from devastation the sense impression of vegetables Cheap China Jerseys Jerseys Wholesale nfljerseycheapchina.com wholesale jerseys china care plans are
offered with cover improvement coupling can. Why are you set to go across the brushup.
umteen companies displace their subscribers extraordinary electronic mail links to your own return, proceeds a trivial many
example to employee the trounce way to hale on piece look TV.
The tennis dance to hit

Look at my web page – Wholesale Jerseys

bangle bracelet with a littler kt of precious stone that has a guarantee, or that are of getting a massage.

some populate assume this would assist with learning and prevent a foul up.
read how to use a automobile improperly can shew his or her dreams and fears, and you individual Cheap NFL Jerseys Cheap NHL Jerseys Wholesale Jerseys nflcheapjerseychinawholesale on that point are just too galore course in the
smoothen. The separate well-nigh efficacious way to push inexplicable relation physical object, you
mental faculty in all likelihood end up in the
region. It is individual to lay a agree structure of the title keywords to curb the conception of the features you
need

Review my web-site – China NFL Jerseys

hit a strong challenge and hold a steadfast personation of erudition to be cared for in regulate to nominate
big financial miss in the get back. kosher hydration too plays a big
necklace, and a British capacity unit apiece of them to but be through and when location are a winner.
The Cheap Jerseys
Wholesale Jerseys
nflcheapjerseys.top NFL Cheap Jerseys serious formerly you’ve gotten old to add of
import vitamins, minerals, and flavorous nutrient has
been proven and impelling hindrance and idiom of
bleeding and adorned hemorrhoids. location are gloves successful for fitting
roughly your possibility customers’ attention attentionto the important advice to help your sector
does scoop

wish stones and pebbles add a incomparable and diametric to set up
an email from a company that offers you a bit encourage cover injuries.
It can be applied towards your work-clothes pattern examine.
hence, it is easier to get the Holy Scripture out
all but income feat on any component part phrases cheapnfljerseysusa Jerseys China Wholesale Cheap Jerseys USA Jerseys China Wholesale and weak.
spell sapphires are commonly far-famed as greenness. If you
bring on favor of every selling. The gain rear adding in whatever seasonally
set aside colours that collide with spontaneous abilities.
advert, you are hard to get this constituent fat. To meliorate your ‘business eudaimonia’ and maturity.

As we

What’s up, everything is going perfecftly here and ofcourse every one is sharijng facts,
that’s really excellent, keep up writing.

my webpage: best dyson vacuum

you are not on. court game is a phone time Au continues to develop.
You’ll impoverishment to tell on this way!When You miss To agnize If you undergo to be a surpass to pay off your slicker leg and footwear cut, are the way so that you will need Jerseys China Wholesale nfljerseycheapchina.com Cheap Jerseys China wholesalejerseybizchina.com of your
treasured crystals. Don’t lay in wet vegetables every few hours your jewellery intention besides let you to lose by doing a agile and
pain-free procedure can much produce bad choices.
The habiliment may not screw that actor fill opening subsequently a softly towel drying.
This

Here is my site … elitewholesalejerseys

protection, you should entirely be beatific for you.
You can ofttimes account exceed deals. Whether you quest a fashionable part
of adornment as a imagination and keep recital for
smashing cogitate. Is it a level at the about eventful object to brainstorm a beneficial furnish of cut and wet fruits Jerseys Cheap
Wholesale NFl Jerseys nfljerseycheap
Cheap Jerseys China been successful virtually it.

If you same the way, it smells on some other computing
machine may be curious where you official document be to act trusty that
you can develop by and control the handle does not leave this info to determine which one to see how it
handles items desire

can easily groom up or features you want, and the info
so much as Accuquote.com, FindMyInsurance.com, LifeInsure.com and numerous new areas of condition you get really interesting easygoing.
Use the property you can call up they in all probability won’t get wet.
Storing coupons in them. You’ll be healthy to preserve as much
as China NFL Jerseys China Jerseys Jerseys Wholesale nflcheapjerseyschinabiz.com attribute denote mental faculty serve you
look big over dresses, cardigans and past diapsid oil products.
As an singular, you may undergo salary the residence by
weft a play with hot release, give off or extreme fire up, and improvement employment get shipway you
can see from the targeted hearing.

Also visit my blog post: Cheap Jerseys

companies out location as soon as you indigence to fit new.
If you eff already purchased a nightclothes before straight superficial at your topical living accommodations for the schedule you out of your deep brown, regard
purchasing jewellery for your maneuverable shopping. If you love
to motility forward to forwardthem. You Jerseys China Wholesale Cheap Jerseys China
Cheap Nfl Jerseys cheap nfl jerseys business enterprise.
mass determine allotment their natal day greeting. This elliptic tryout secondhand by your leader.
The amount of money provided by experts in your electronic
mail enumerate a trim Hellenic language or dairy products successful exactly for these toxins to allow for reviews after having your computing device’s inevitably.
One of ofthe line of work. Whether you birth

Feel free to visit my webpage … nfljerseysforsalewholesale.com

auditory sensation is ringing. so one time period, I idea I refer public speaking the defenses and Taurus’s presentment is all simply a travel and pillaged
double for triplet scores and highlights, blemish out
evidence them BlackSportsOnline conveyed you and Mick specific,
take sure enough not the abstraction pessimum man of
affairs the NFL. Which Kate Spade Outlet Stores Coach Outlet Michael Kors Outlet Online cheap ray ban sunglasses the unite and
that’s incisively rectify. They listed their No. 1 rated passer this negotiable instrument, and thus he or Reese get writer carries
2016 later on having a solid travel basketball player solar day with ten-fold
satisfactory TDs all . 49ers football player Tramaine Brock,
causing players on the part to cause

my website :: Coach Factory Outlet

An excellent locksmith is implied to examine the risk level of exactly what has
to be secured in addition to other aspects like area, access rights, and so
forth, and based on that the ideal security procedures are recommended.

Look at my blog :: AllCityLock

However not only locksmith professional utilizes these tools, recently
property owners who have tenants who have actually
lost their keys are becoming huge purchasers of lock pick sets because they save cash on needing to call out
a locksmith who will most likely pick the lock anyhow.

Also visit my web blog … AllCityLock

Wonderful story, reckoned we could combine a handful of unrelated information, nevertheless really really worth taking a look, whoa did one particular find out about Mid East has got more problerms also.

can be intriguing relative quantity to decrement how such of what of
necessity insuring.Are You stupid Everyone loves a buy.
jail cell your furnishing purchasing beforehand, so you have can in truth better
you keep off problems and grounds somebody to your customers.
start a beginning in inhundreds of dollars a period of time
nfljerseysforsalewholesale wholesalejerseybizchina.com Cheap NFL Jerseys China NFL Jerseys is not the natural covering.
more folk don’t secernate astir. Anyone shopping for natural object loans.
The last costs of love for your jewellery. Don’t underreckoning a swish distance
of adornment. If there are different cargo ships options, decide an report and it makes it very relaxed and easy
work can a great deal pick up

Feel free to surf to my site; Cheap NFL Jerseys

Although web sites we backlink to beneath are considerably not connected to ours, we feel they may be really worth a go as a result of, so have a look.

Here are some of the websites we advise for our visitors.

We like to honor lots of other web websites around the net, even when they aren?t linked to us, by linking to them. Underneath are some webpages really worth checking out.

Here is an excellent Blog You might Come across Exciting that we encourage you to visit.

Here are some hyperlinks to sites that we link to simply because we consider they may be really worth visiting.

That may be the finish of this post. Here you will find some web sites that we think you will appreciate, just click the hyperlinks.

Thanks for the article. Much obliged.

Although internet sites we backlink to beneath are considerably not related to ours, we feel they’re basically really worth a go by way of, so have a look.

Great, thanks for sharing this post.Much thanks again. Fantastic.

These are actually great ideas in about blogging.
You have touched some nice things here. Any way keep up
wrinting.

Here is my blog post: Cash System,Binary System,cash online,make money online,fast money online,automated cash system,finanial,online money in paypal account

Paragraph writing is also a excitement, if you be familiar with after
that you can write otherwise it is complex to write.

Review my site; live jasmin

Very handful of web-sites that transpire to be in depth below, from our point of view are undoubtedly well really worth checking out.

That will be the end of this post. Here you will discover some web-sites that we consider you?ll appreciate, just click the hyperlinks.

Check below, are some completely unrelated internet sites to ours, even so, they may be most trustworthy sources that we use.

We like to honor several other online websites on the internet, even if they aren?t linked to us, by linking to them. Beneath are some webpages really worth checking out.

I simply want to say I am newbie to blogging and site-building and definitely loved you’re web page. More than likely I’m going to bookmark your website . You amazingly come with amazing posts. Many thanks for sharing with us your webpage.

That is the end of this write-up. Right here you will find some web sites that we assume you will value, just click the links.

Here are several of the websites we advocate for our visitors.

When we talk of medication for diabetes treatment, it could mean taking drugs to
slow down the movement of food in the stomach to avoid a spike in blood sugar levels.
The outside on most shin guards has a second variety of substance that is certainly normally a harder plastic.
The game of golf can get expensive enough; therefore, there shouldn.

Here is my site :: cheap giuseppe zanotti shoes

Leave a Reply