PageRenderTime 11ms CodeModel.GetById 2ms app.highlight 4ms RepoModel.GetById 2ms app.codeStats 0ms

/trunk/Examples/ruby/funcptr/index.html

#
HTML | 90 lines | 66 code | 24 blank | 0 comment | 0 complexity | cba1b1cd74b91f0a9a813d4503f8d5a4 MD5 | raw file
 1<html>
 2<head>
 3<title>SWIG:Examples:ruby:funcptr</title>
 4</head>
 5
 6<body bgcolor="#ffffff">
 7
 8
 9<tt>SWIG/Examples/ruby/funcptr/</tt>
10<hr>
11
12<H2>Pointers to Functions</H2>
13
14<p>
15Okay, just what in the heck does SWIG do with a declaration like this?
16
17<blockquote>
18<pre>
19int do_op(int a, int b, int (*op)(int, int));
20</pre>
21</blockquote>
22
23Well, it creates a wrapper as usual.  Of course, that does raise some
24questions about the third argument (the pointer to a function). 
25
26<p>
27In this case, SWIG will wrap the function pointer as it does for all other
28pointers.  However, in order to actually call this function from a script,
29you will need to pass some kind of C function pointer object.  In C,
30this is easy, you just supply a function name as an argument like this:
31
32<blockquote>
33<pre>
34/* Some callback function */
35int add(int a, int b) {
36   return a+b;
37} 
38...
39int r = do_op(x,y,add);
40</pre>
41</blockquote>
42
43To make this work with SWIG, you will need to do a little extra work.  Specifically,
44you need to create some function pointer objects using the %constant directive like this:
45
46<blockquote>
47<pre>
48%constant(int (*)(int,int)) ADD = add;
49</pre>
50</blockquote>
51
52Now, in a script, you would do this:
53
54<blockquote>
55<pre>
56r = do_op(x,y, ADD)
57</pre>
58</blockquote>
59
60<h2>An Example</h2>
61
62Here are some files that illustrate this with a simple example:
63
64<ul>
65<li><a href="example.c">example.c</a>
66<li><a href="example.h">example.h</a>
67<li><a href="example.i">example.i</a> (SWIG interface)
68<li><a href="runme.rb">runme.rb</a> (Sample script)
69</ul>
70
71<h2>Notes</h2>
72
73<ul>
74<li>The value of a function pointer must correspond to a function written in C or C++.
75It is not possible to pass an arbitrary Ruby proc object in as a substitute for a C 
76function pointer.
77
78<p>
79<li>A ruby proc can be used as a C/C++ callback if you write some
80clever typemaps and are very careful about how you create your extension.
81This is an advanced topic not covered here.
82</ul>
83
84<hr>
85</body>
86</html>
87
88
89
90