Google

SWIG/Examples/perl5/simple/

Simple Perl5 Example

$Header: /cvs/projects/SWIG/Examples/perl5/simple/index.html,v 1.1 2000/06/17 23:46:23 beazley Exp $

This example illustrates how you can hook Perl to a very simple C program containing a function and a global variable.

The C Code

Suppose you have the following C code:
/* 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;
}

The SWIG interface

Here is a simple SWIG interface file:
/* File: example.i */
%module example

extern int gcd(int x, int y);
extern double Foo;

Compilation

  1. swig -perl5 example.i

  2. This produces two files: example_wrap.c and example.pm.

  3. Compile example_wrap.c and example.c to create the extension example.so.

Using the extension

Click here to see a script that calls our C functions from Perl.

Key points

  • Use the use statement to load your extension module from Perl. For example:
    use example;
    
  • C functions work just like Perl functions. For example:
    $g = example::gcd(42,105);
    
  • C global variables are accessed like ordinary Perl variables. For example:
    $a = $example::Foo;