views:

47

answers:

1

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 &'.

A: 

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?

Mike Ellery
Not the very latest, but SWIG Version 1.3.29. But I don't expect that this has changed recently.
fuenfundachtzig