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