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.

A More Complex Example for Ruby

I recently had occassion to decrypt and encrypt data to authenticate communication between a client and a server. Here’s the scheme:

  1. When contact is initiated by a client, the server replies with a message signed with a shared, secret key. Part of the message is a signature assigned to the client.
  2. Upon receipt of the reply, the client decrypts the message and extracts the signature assigned to it by the server.
  3. To make additional requests, the client must include the signature and sign the request with the shared, secret key.
  4. If the server cannot decrypt the message or does not see the assigned signature, the request is ignored.

In this case, each missive was also encoded in Base64 to transmit it as plain text. The encryption technique was DES ECB.

To make this interchange work with Rails, I created a small extension for Ruby based on mcrypt. Here is the code, secret.c, with the secret eight-character key changed to something innocuous.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mcrypt.h>

char *encode( char *string, int length );
char *decode( char *string, int length );

MCRYPT start() {
  MCRYPT td = mcrypt_module_open( "des", NULL, "ecb", NULL );
  if ( td == MCRYPT_FAILED ) {
    return( MCRYPT_FAILED );

  if ( mcrypt_enc_self_test( td ) != 0 ) {
    return( MCRYPT_FAILED );

  int i;
  char *IV;
  int iv_size = mcrypt_enc_get_iv_size( td );
  if ( iv_size != 0 ) {
    IV = calloc( 1, iv_size );
    for ( i = 0; i < iv_size; i++ ) {
      IV[ i ] = rand();

  int keysize = mcrypt_enc_get_key_size( td );
  char *key = calloc( 1, keysize );
  memcpy(key, "SECRET!!", keysize);

  i = mcrypt_generic_init ( td, key, keysize, IV );
  if ( i < 0 ) {
    mcrypt_perror( i );

  return( td );

void end( MCRYPT td ) {
  mcrypt_generic_deinit( td );
  mcrypt_module_close( td );

#define B64_DEF_LINE_SIZE   72
#define B64_MIN_LINE_SIZE    4

** encode 3 8-bit binary bytes as 4 '6-bit' characters
void encodeblock( unsigned char in[3], unsigned char out[4], int len ) {
    static const char cb64[]
    out[0] = cb64[ in[0] >> 2 ];
    out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
    out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) |
      ((in[2] & 0xc0) >> 6) ] : '=');
    out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');

char *base64encode( char *input, int size ) {
    int i, x, len;
    unsigned char in[3], out[4];
    char *target = calloc( 1, ( ( size + 2 ) / 3 ) * 4 + 1 );
    char *t = target;

    for ( x = 0; x < size; ) {
        len = 0;

        for( i = 0; i < 3; i++ ) {
            if ( x < size ) {
              in[i] = input[x++];
            else {
                in[i] = 0;

        if( len ) {
            encodeblock( in, out, len );
            for( i = 0; i < 4; i++ ) {
                *t++ = out[i];

    return( target );

char *encode( char *string, int length ) {
  MCRYPT td = start();
  int blocksize = mcrypt_enc_get_block_size( td );
  int cryptsize = ( ( length  + blocksize - 1 ) / blocksize ) * blocksize;
  char *target = calloc( 1,  cryptsize );

  memcpy( target, string, length );

  if ( mcrypt_generic( td, target, cryptsize ) != 0 ) {
      fprintf( stderr, "Code failing" );

  end( td );

  char* result = base64encode( target, cryptsize );

  free( target );
  return result;

char *decode( char *string, int length ) {
  MCRYPT td = start();
  int blocksize = mcrypt_enc_get_block_size( td );
  char *block_buffer = calloc( 1, blocksize );
  int decryptlength = (length + blocksize - 1) / blocksize * blocksize;
  char *target = calloc( 1, decryptlength );

  memcpy(target, string, length);

  mdecrypt_generic( td, target, decryptlength ); 

  end( td );

  return( target );

The Rails code uses encode() and decode() to encrypt and decrypt strings, respectively. The rationale for formal arguments char *string, int length is explained below.

The rest of the code shown merely supports those two functions. For example, encode() calls base64encode() as a convenience, since whatever is encrypted has to be encoded too before it is sent.

Here’s the rather spartan secret.i, the SWIG interface for the extension.

%module secret

%include "typemaps.i"

  #include "ruby.h"

%newobject encode;
%newobject decode;
%apply (char *STRING, int LENGTH) { ( char *string, int length ) };

char *encode( char *string, int length );
char *decode( char *string, int length );

Let’s walk though the SWIG code.

  • The first line names the extension secret. The Rails code includes the extension with require 'secret'.
  • The line %include "typemaps.i" imports a SWIG library that helps simplify argument conversion between the host language and the extension. Here, one of those special conversions bridges the call to encode() and decode() from Ruby to the underlying C code.

    Specifically, calls to encode() and decode() in Ruby provide a single argument, the binary data of the outgoing or incoming encrypted message, respectively. (In other words, calls look like encode(request) and decode(reply).) However, to exchange the data with the extension, the single argument must be converted to a string and a count. The special typemap …

    %apply (char *STRING, int LENGTH) { ( char *string, int length ) }

    … treats the phrase ( char *string, int length ) anywhere it appears as a single argument and promotes it to two arguments. Hence, the definitions…

    char *encode( char *string, int length );
    char *decode( char *string, int length );

    specify that these two functions are called with a single actual argument and SWIG converts it to two actual arguments when passed on to the extension and vice versa from extension to language.

  • Much like Perl required its header files to build the extension, Ruby requires ruby.h. This line of code is added to secret_wrap.c, the output of SWIG.
  • Finally, the two %newobject operands specify that each of encode() and decode() return new objects that SWIG must subsequently free to prevent memory leaks.

Building the extension is just three steps. An additional file unique to Ruby creates a Makefile to automate the process.

$ swig -ruby secret.i
$ cat extconf.rb
# Loads mkmf which is used to make makefiles for Ruby extensions
require 'mkmf'

# Give it a name
extension_name = 'secret'

# Add a library
$libs = append_library($libs, "mcrypt")

# The destination

# Do the work

$ ruby extconf.rb
$ make
cc -I. -I/usr/lib/ruby/1.8/i486-linux -I/usr/lib/ruby/1.8/i486-linux -I.
  -D_FILE_OFFSET_BITS=64  -fPIC -fno-strict-aliasing -g -g -O2  -fPIC   -c secret.c
cc -I. -I/usr/lib/ruby/1.8/i486-linux -I/usr/lib/ruby/1.8/i486-linux -I.
  -D_FILE_OFFSET_BITS=64  -fPIC -fno-strict-aliasing -g -g -O2  -fPIC   -c secret_wrap.c
cc -shared -o secret.so secret.o secret_wrap.o -L. -L/usr/lib -L.  -rdynamic
  -Wl,-export-dynamic    -lruby1.8 -lmcrypt  -lpthread -ldl -lcrypt -lm   -lc

The extension is now ready to use.

dcauto% irb
irb(main):001:0> require 'secret'
=> true
irb(main):002:0> message = "hello"
=> "hello"
irb(main):003:0> puts Secret.encode(message)
irb(main):004:0> require 'base64'
=> true
irb(main):005:0> puts Secret.decode(Base64.decode64(Secret.encode(message)))
=> nil

Take a Swig!

SWIG is very rich and a thorough reading of the documentation is worthwhile and warranted. If you have C or C++ code you want to repurpose, SWIG can make that old code cool once again.

I’d like to thank Unix developer Barry Stone for his assistance squashing the (originally) errant pointers in my C code.

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.

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

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.

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

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