Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swig: How to wrap double& (double passed by reference)?

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

like image 229
fuenfundachtzig Avatar asked Aug 12 '10 18:08

fuenfundachtzig


2 Answers

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.)

like image 94
sambha Avatar answered Oct 21 '22 09:10

sambha


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.)

like image 1
Professor Nuke Avatar answered Oct 21 '22 09:10

Professor Nuke