/trunk/Examples/python/simple/index.html
HTML | 97 lines | 74 code | 23 blank | 0 comment | 0 complexity | 70286da65ef6e2ea73c1b27b851067a6 MD5 | raw file
1<html> 2<head> 3<title>SWIG:Examples:python:simple</title> 4</head> 5 6<body bgcolor="#ffffff"> 7 8 9<tt>SWIG/Examples/python/simple/</tt> 10<hr> 11 12<H2>Simple Python Example</H2> 13 14<p> 15This example illustrates how you can hook Python to a very simple C program containing 16a function and a global variable. 17 18<h2>The C Code</h2> 19 20Suppose you have the following C code: 21 22<blockquote> 23<pre> 24/* File : example.c */ 25 26/* A global variable */ 27double Foo = 3.0; 28 29/* Compute the greatest common divisor of positive integers */ 30int gcd(int x, int y) { 31 int g; 32 g = y; 33 while (x > 0) { 34 g = x; 35 x = y % x; 36 y = g; 37 } 38 return g; 39} 40</pre> 41</blockquote> 42 43<h2>The SWIG interface</h2> 44 45Here is a simple SWIG interface file: 46 47<blockquote> 48<pre> 49/* File: example.i */ 50%module example 51 52extern int gcd(int x, int y); 53extern double Foo; 54</pre> 55</blockquote> 56 57<h2>Compilation</h2> 58 59<ol> 60<li><tt>swig -python <a href="example.i">example.i</a></tt> 61<p> 62<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt> 63to create the extension <tt>examplemodule.so</tt>. 64</ol> 65 66<h2>Using the extension</h2> 67 68Click <a href="example.py">here</a> to see a script that calls our C functions from Python. 69 70<h2>Key points</h2> 71 72<ul> 73<li>Use the <tt>import</tt> statement to load your extension module from Python. For example: 74<blockquote> 75<pre> 76import example 77</pre> 78</blockquote> 79 80<li>C functions work just like Python functions. For example: 81<blockquote> 82<pre> 83g = example.gcd(42,105) 84</pre> 85</blockquote> 86 87<li>C global variables are accessed through a special variable called 'cvar'. For example: 88<blockquote> 89<pre> 90a = example.cvar.Foo 91</pre> 92</blockquote> 93</ul> 94 95<hr> 96</body> 97</html>