Discussion:
[Swig-user] Treat Returned Reference as Value
Jake
2017-05-18 14:05:49 UTC
Permalink
I feel like I must just be missing this in the documentation somewhere, but
when a function returns a reference SWIG treats that like a pointer by
default. How do we tell it to treat it as a value (i.e. make a copy and
wrap that)?

For example:

struct Example {
int& get(int x, int y);
};

I want the int copied and not as a SWIG_int_p.

-Jake Cobb
schullq
2017-05-18 14:14:47 UTC
Permalink
Do you include "typemaps.i" ?

If not, include it, and take a look a it ([swig folder]/Lib/[your target
language]/typemaps.i]), you should get your answer here.



--
View this message in context: http://swig.10945.n7.nabble.com/Treat-Returned-Reference-as-Value-tp15163p15164.html
Sent from the swig-user mailing list archive at Nabble.com.
William S Fulton
2017-05-19 06:58:22 UTC
Permalink
Post by Jake
I feel like I must just be missing this in the documentation somewhere,
but when a function returns a reference SWIG treats that like a pointer by
default. How do we tell it to treat it as a value (i.e. make a copy and
wrap that)?
struct Example {
int& get(int x, int y);
};
I want the int copied and not as a SWIG_int_p.
const int& is marshalled by value in Java/C#. You can thus simply use these
typemaps. There are various ways, but I suggest using %apply:

%apply const int& { int& } // Everywhere (including input parameters and
on function return)

%apply const int& { int& Example::get} // Just for this function's return
Post by Jake
Do you include "typemaps.i" ?
If not, include it, and take a look a it ([swig folder]/Lib/[your target
language]/typemaps.i]), you should get your answer here.
typemaps.i is for changing the way a function's parameters are marshalled,
so not of any use for a function's return. You'll notice there are no 'out'
typemaps in this file which is what generates the C code for returning
types from a function.

William
Jake
2017-05-31 15:07:12 UTC
Permalink
Post by William S Fulton
%apply const int& { int& Example::get} // Just for this function's return
I think this is what I'm looking for since std::vector wrapping provided by
std_vector.i
has a non-const return on operator[]. Thanks.

-Jake Cobb

Loading...