问题
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 &'
.
回答1:
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.)
回答2:
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.)
回答3:
hmm - are you using the latest version of SWIG? The documentation seems to indicate that this works -- from the manual:
C++ references are supported, but SWIG will treat them as pointers. For example, a declaration like this :
class Foo { public: double bar(double &a); }
will be accessed using a function like this :
double Foo_bar(Foo *obj, double *a) { obj->bar(*a); }
Functions returning a reference will be mapped into functions returning pointers.
I don't know how you map that on the python side...does python have something like perl references?
来源:https://stackoverflow.com/questions/3470641/swig-how-to-wrap-double-double-passed-by-reference