/tags/rel-1.3.35/Examples/perl5/simple/index.html
HTML | 99 lines | 76 code | 23 blank | 0 comment | 0 complexity | f8ed18928511d41e8cd26ebcb3d8a788 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:perl5:simple</title>
4</head>
5
6<body bgcolor="#ffffff">
7
8
9<tt>SWIG/Examples/perl5/simple/</tt>
10<hr>
11
12<H2>Simple Perl5 Example</H2>
13
14<p>
15This example illustrates how you can hook Perl 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 -perl5 <a href="example.i">example.i</a></tt>
61<p>
62<li>This produces two files: <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.pm">example.pm</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>example.so</tt>.
66</ol>
67
68<h2>Using the extension</h2>
69
70Click <a href="runme.pl">here</a> to see a script that calls our C functions from Perl.
71
72<h2>Key points</h2>
73
74<ul>
75<li>Use the <tt>use</tt> statement to load your extension module from Perl. For example:
76<blockquote>
77<pre>
78use example;
79</pre>
80</blockquote>
81
82<li>C functions work just like Perl functions. For example:
83<blockquote>
84<pre>
85$g = example::gcd(42,105);
86</pre>
87</blockquote>
88
89<li>C global variables are accessed like ordinary Perl variables. For example:
90<blockquote>
91<pre>
92$a = $example::Foo;
93</pre>
94</blockquote>
95</ul>
96
97<hr>
98</body>
99</html>