SWIG: How to pass list of complex from c++ to python

早过忘川 提交于 2019-12-22 12:09:33

问题


I have a function in c++ who returns a list of complex:

#include <complex>
std::list< std::complex<double> > func(...);

what should i do in the '*.i' file ?

Thank you every body.

=================

Following are details:

the function i would like to use in python in x.h:

std::list<std::complex<double> > roots1(const double& d, const double& e);

I have tried some ways:

(1) x.i:

%include <std_list.i>
%include <std_complex.i>

than I try in IPython:

tmp = x.roots1(1.0, 2.0)
len(tmp)

and I got:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-9ebf7dab7cd9> in <module>()
----> 1 len(tmp)

TypeError: object of type 'SwigPyObject' has no len()

and:

dir(tmp)

returns:

[ 
...
'acquire',
'append',
'disown',
'next',
'own']

(2) x.i:

%include <std_list.i>
%include <std_complex.i>
namespace std {
    %template(ComplexDouble)        complex<double>;
}

than, i got compile error:

error: command 'swig' failed with exit status 1
make: *** [py] Error 1

(3) in x.i:

%include <std_list.i>
%include <std_complex.i>
namespace std {
    %template(ComplexDouble)        list<complex<double> >;
}

or:

%include <std_list.i>
%include <std_complex.i>
namespace std {
    %template(ComplexDouble)        list<complex>;
}

and I got:

x_wrap.cpp:5673:32: error: ‘complex’ was not declared in this scope
 template <>  struct traits<complex > {
                            ^

================================================

(Mr./Ms./Mrs) m7thon help me find the problem. In my python context:

Ubuntu: 45~14.04.1
Python:  3.4.3
SWIG:    SWIG Version 2.0.11
         Compiled with g++ [x86_64-unknown-linux-gnu]
         Configured options: +pcre

if define the x.i as:

%include <std_list.i>
%include <std_complex.i>
namespace std {
    %template(ComplexList)        list<complex<double> >;
}

there will be compiling error. But it works if x.i:

%include <std_list.i>
%include <std_complex.i>
%template(ComplexList) std::list< std::complex<double> >;

Thank you m7thon.


回答1:


This works:

%include <std_list.i>
%include <std_complex.i>
%template(ComplexList) std::list<std::complex<double> >;
... (your includes / function declarations)

I think your version (3) should actually also work. Strange that it doesn't. Maybe a SWIG bug.




回答2:


To be more concise you can use the whole namespace:

%include <std_list.i>
%include <std_complex.i>

using namespace std;

%template(ComplexList) list<complex<double> >;

But the initially suggested versions of including SWIG %template into the std namespace is not a good idea.



来源:https://stackoverflow.com/questions/38023521/swig-how-to-pass-list-of-complex-from-c-to-python

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