PageRenderTime 7ms CodeModel.GetById 1ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/ruby/simple/index.html

#
HTML | 97 lines | 74 code | 23 blank | 0 comment | 0 complexity | a3bbf45c2210f6e67014b554c84ffa54 MD5 | raw file
 1<html>
 2<head>
 3<title>SWIG:Examples:ruby:simple</title>
 4</head>
 5
 6<body bgcolor="#ffffff">
 7
 8
 9<tt>SWIG/Examples/ruby/simple/</tt>
10<hr>
11
12<H2>Simple Ruby Example</H2>
13
14<p>
15This example illustrates how you can hook Ruby 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 &gt; 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 -ruby <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>example.so</tt>. 
64</ol>
65
66<h2>Using the extension</h2>
67
68Click <a href="run.rb">here</a> to see a script that calls our C functions from Ruby.
69
70<h2>Key points</h2>
71
72<ul>
73<li>Use the <tt>require</tt> function to load your extension library from Ruby. For example:
74<blockquote>
75<pre>
76require 'example'
77</pre>
78</blockquote>
79
80<li>C functions work just like Ruby 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 module method. For example:
88<blockquote>
89<pre>
90a = Example.Foo
91</pre>
92</blockquote>
93</ul>
94
95<hr>
96</body>
97</html>