Abolfazl Abolfazl - 9 months ago 149
Python Question

SWIG: How to pass a vector of complex numbers from C++ to python

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:

example.i



%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"


example.cpp



#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;
}


example.h



#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();
};


I compiled and give me the following error when I try to test it:

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


I don't know Where I made a mistake?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download