3
<title>SWIG:Examples:ruby:pointer</title>
6
<body bgcolor="#ffffff">
8
<tt>SWIG/Examples/ruby/pointer/</tt>
11
<H2>Simple Pointer Handling</H2>
13
<tt>$Header: /cvs/projects/SWIG/Examples/ruby/pointer/index.html,v 1.1 2000/09/18 13:21:26 fukusima Exp $</tt><br>
16
This example illustrates a couple of techniques for handling
17
simple pointers in SWIG. The prototypical example is a C function
18
that operates on pointers such as this:
22
void add(int *x, int *y, int *r) {
28
By default, SWIG wraps this function exactly as specified and creates
29
an interface that expects pointer objects for arguments. The only
30
problem is how does one go about creating these objects from a script?
32
<h2>Possible Solutions</h2>
35
<li>Write some helper functions to explicitly create objects. For
40
int *new_int(int ivalue) {
41
int *i = (int *) malloc(sizeof(ivalue));
49
void delete_int(int *i) {
55
Now, in a script you would do this:
64
print "Result = #{r}\n"
72
<li>Use the SWIG pointer library. For example, in the interface file
81
and in a script you would do this:
85
a = ptrcreate("int",37)
86
b = ptrcreate("int",42)
90
print "Result = #{r}\n"
97
The advantage to using the pointer library is that it unifies some of the helper
98
functions behind a common set of names. For example, the same set of functions work
99
with int, double, float, and other fundamental types.
102
<li>Use the SWIG typemap library. This library allows you to completely
103
change the way arguments are processed by SWIG. For example:
107
%include "typemaps.i"
108
void add(int *INPUT, int *INPUT, int *OUTPUT);
117
print "Result = #{r}\n"
120
Needless to say, this is substantially easier.
123
<li>A final alternative is to use the typemaps library in combination
124
with the %apply directive. This allows you to change the names of parameters
125
that behave as input or output parameters. For example:
129
%include "typemaps.i"
130
%apply int *INPUT {int *x, int *y};
131
%apply int *OUTPUT {int *r};
133
void add(int *x, int *y, int *r);
134
void sub(int *x, int *y, int *r);
135
void mul(int *x, int *y, int *r);
144
The following example illustrates the use of these features for pointer
148
<li> <a href="example.c">example.c</a> (C Source)
149
<li> <a href="example.i">example.i</a> (Swig interface)
150
<li> <a href="runme.rb">runme.rb</a> (Ruby Script)
156
<li>Since pointers are used for so many different things (arrays, output values,
157
etc...) the complexity of pointer handling can be as complicated as you want to
161
<li>More documentation on the typemaps.i and pointer.i library files can be
162
found in the SWIG user manual. The files also contain documentation.
165
<li>The pointer.i library is designed primarily for convenience. If you
166
are concerned about performance, you probably want to use a different