I am using SWIG to access C++ code from Python. How do I elegantly wrap a function that returns values in variables passed by reference like
void set(double&a) {
a = 42.;
}
I could not find out how to do this. In the best case I'd be able to use the function in Python with Python floats:
>>> b = 2.
>>> set(b)
>>> print b
42.0
At the moment it gives me a TypeError: in method 'TestDouble_set', argument 2 of type 'double &'
.
Do it this way:
Your swig interface file:
%include <typemaps.i>
%apply double& INOUT { double& a };
void set(double& a);
Usage in python script:
a = 0.0
a = set(a)
print a
If your function returns something (instead of being a void), do the below in python
ret, a = set(a)
Checkout the documentation for typemaps in swig. You can do INPUT, OUTPUT & INOUT for arguments. HTH
Note that this solution relies on the SWIG-provided OUTPUT typemaps defined in typemaps.i
library, which pre-defines the typemaps being used by the %apply
command above.
typemaps.i
defines input/output typemaps for C++ primitive types (see the above link to the SWIG documentation for more info); however, you have into include the typemaps.i library in your interface file for SWIG to use them. (Hence why some commenters likely found the original solution wasn't working for them.)
Note that the accepted (correct) solution relies on the SWIG-provided OUTPUT typemaps defined in typemaps.i
library, which pre-defines the typemaps being used by the %apply
command above.
typemaps.i
defines input/output typemaps for C++ primitive types (see the above link to the SWIG documentation for more info); however, you have to include the typemaps.i library in your interface file for SWIG to use them. (Hence why some commenters likely found the original solution wasn't working for them.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With