3 <title>SWIG:Examples:perl5:reference</title>
6 <body bgcolor="#ffffff">
9 <tt>SWIG/Examples/perl5/reference/</tt>
12 <H2>C++ Reference Handling</H2>
15 This example tests SWIG's handling of C++ references. Since C++
16 references are closely related to pointers (as both refer to a
17 location in memory), SWIG simply collapses all references into
18 pointers when creating wrappers.
20 <h2>Some examples</h2>
22 References are most commonly used as function parameter. For example,
23 you might have an operator like this:
27 Vector operator+(const Vector &a, const Vector &b) {
41 Vector addv(const Vector &a, const Vector &b) {
51 In these cases, SWIG transforms everything into a pointer and creates a wrapper
56 Vector wrap_addv(Vector *a, Vector *b) {
62 Occasionally, a reference is used as a return value of a function
63 when the return result is to be used as an lvalue in an expression.
64 The prototypical example is an operator like this:
68 Vector &operator[](int index);
76 Vector &get(int index);
80 For functions returning references, a wrapper like this is created:
84 Vector *wrap_Object_get(Object *self, int index) {
85 Vector &result = self->get(index);
91 The following <a href="example.h">header file</a> contains some class
92 definitions with some operators and use of references.
94 <h2>SWIG Interface</h2>
96 SWIG does NOT support overloaded operators so it can not directly build
97 an interface to the classes in the above file. However, a number of workarounds
98 can be made. For example, an overloaded operator can be stuck behind a function
99 call such as the <tt>addv()</tt> function above. Array access can be handled
100 with a pair of set/get functions like this:
108 Vector &get(int index) {
109 return (*self)[index];
111 void set(int index, Vector &a) {
120 Click <a href="example.i">here</a> to see a SWIG interface file with these additions.
122 <h2>Sample Perl script</h2>
124 Click <a href="runme.pl">here</a> to see a script that manipulates some C++ references.
129 <li>C++ references primarily provide notational convenience for C++
130 source code. However, it doesn't much matter to Perl.
133 <li>When a program returns a reference, a pointer is returned.
134 Unlike return by value, memory is not allocated to hold the
138 <li>SWIG has particular trouble handling various combinations of references
139 and pointers. This is side effect of an old parsing scheme and
140 type representation that will be replaced in future versions.