Python SWIG Example


This is the example from the docs, properly fixed and portable to compile on Linux and Mac OS X (Snow Leopard).

For the files and other possible information, see my GitHub example at http://github.com/arcoleo/pycpp/swig.

This tutorial assumes you have install SWIG. If you have not, see http://github.com/arcoleo/pycpp/swig.

Files#

You need three files - Makefile, example.c, example.i.

Makefile#

OS := $(shell uname)

CC=gcc
CXX=g++

ifeq ($(OS), Darwin)
	CFLAGS=-g -c
	LD=gcc
	LDFLAGS=-bundle -flat_namespace -undefined suppress
else
	CFLAGS=-g -c -fPIC
	LD=ld
	LDFLAGS=-shared
endif

all: 1_example

1_example: example.c
	swig -python example.i
	$(CC) $(CFLAGS) example.c example_wrap.c -I/usr/include/python2.6 -I/usr/lib/python2.6
	$(LD) $(LDFLAGS) -o _example.so example.o example_wrap.o

clean:
	rm -f *.o
	rm -f *.pyc
	rm -f *.so
	rm -f example_wrap.c
	rm -f example.py

example.c#

#include <time.h>
#include <string.h>

double My_variable = 3.0;

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

int my_mod(int x, int y) {
    return (x % y);
}

char *get_time() {
    time_t ltime;
    time(&ltime);
    return ctime(&ltime);
}

example.i#

 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}

 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 

Compile & Test#

Compile

$ make

Test from a python shell

>>> import example
>>> example.fact(5)
120
>>> example.my_mod(7,3)
1
>>> example.get_time()
'Sun Feb 11 23:01:07 1996'
>>>

Python - C/C++