I need to pass a list of complex numbers from python to C++ to initialize a vector and after some operations, I need to pass the vector of complex double back to python.
Here is my try:
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include "std_vector.i"
%include <complex.i>
%include <std_complex.i>
namespace std {
%template(DoubleVector) vector<double>;
%template(ComplexVector) vector<std::complex<double> >;
}
%include "example.h"
#include "example.h"
void my_class::set_value(Complex a, std::vector<Complex> v)
{
com1 = {1,2};
comV = v;
}
void my_class::print_value()
{
std::cout << com1<< std::endl;
for (int i=0; i<comV.size(); i++)
std::cout<<comV[i]<<std::endl;
}
#include <iostream>
#include <cstdio>
#include <vector>
#include <omp.h>
#include <complex>
typedef std::complex<double> Complex;
class my_class
{
private:
Complex com1;
std::vector<Complex> comV;
public:
my_class(){ }
void set_value(Complex a, std::vector<Complex> v);
void print_value();
};
import example
c = example.my_class()
c.set_value(complex(1.0,3.5), [complex(1,1.2), complex(2.0,4.2)])
c.print_value()
return _example.my_class_set_value(self, a, v)
TypeError: in method 'my_class_set_value', argument 3 of type 'std::vector< Complex,std::allocator< Complex > >'
You have to put an explicit instantiation of ComplexVector
in the SWIG-file, otherwise it won't work. Your mistake was that you did not qualify std::complex<double>
properly (you forgot the namespace).
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
%include "std_complex.i"
namespace std {
%template(DoubleVector) vector<double>;
%template(ComplexVector) vector<std::complex<double>>;
}
%include "example.h"
Futhermore my_class::print_value()
is missing a return statement which will lead to an illegal instruction.