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

偶尔善良 提交于 2019-12-03 16:37:43
sambha

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

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!