3
<title>SWIG:Examples:ruby:value</title>
6
<body bgcolor="#ffffff">
9
<tt>SWIG/Examples/ruby/value/</tt>
12
<H2>Passing and Returning Structures by Value</H2>
14
<tt>$Header: /cvs/projects/SWIG/Examples/ruby/value/index.html,v 1.1 2000/09/18 13:21:27 fukusima Exp $</tt><br>
17
Occasionally, a C program will manipulate structures by value such as shown in the
22
/* File : example.c */
24
typedef struct Vector {
28
double dot_product(Vector a, Vector b) {
29
return (a.x*b.x + a.y*b.y + a.z*b.z);
32
Vector vector_add(Vector a, Vector b) {
42
Since SWIG only knows how to manage pointers to structures (not their internal
43
representation), the following translations are made when wrappers are
48
double wrap_dot_product(Vector *a, Vector *b) {
49
return dot_product(*a,*b);
52
Vector *wrap_vector_add(Vector *a, Vector *b) {
53
Vector *r = (Vector *) malloc(sizeof(Vector));
54
*r = vector_add(*a,*b);
60
The functions are then called using pointers from the scripting language interface.
61
It should also be noted that any function that returns a structure by value results
62
in an implicit memory allocation. This will be a memory leak unless you take steps
63
to free the result (see below).
65
<h2>The SWIG interface</h2>
67
Click <a href="example.i">here</a> to see a SWIG interface file that
68
wraps these two functions. In this file, there are a few essential features:
71
<li>A wrapper for the <tt>free()</tt> function is created so that we
72
can clean up the return result created by <tt>vector_add()</tt>
76
<li>The %inline directive is used to create a few helper functions for creating new Vector
77
objects and to print out the value (for debugging purposes).
80
<h2>A Ruby Script</h2>
82
Click <a href="runme.rb">here</a> to see a script that uses these functions from Ruby.
87
<li>When the '<tt>-c++</tt>' option is used, the resulting wrapper code for the return value
88
changes to the following:
92
Vector *wrap_vector_add(Vector *a, Vector *b) {
93
Vector *r = new Vector(vector_add(*a,*b));
100
<li>If you define C structure (or C++ class with '<tt>-c++</tt>' option)
101
in the interface file, the SWIG generated wrappers can automaticallyclean
102
up the result of return-by-reference by GC.
105
<li>Passing parameters by value like this really isn't the best C programming style.
106
If possible, you might change your application to use pointers.
109
<li>Similar translations are made when C++ references are used.