user1512321
user1512321

Reputation:

SWIG: Passing a std::vector< std::vector <double> > pointer to python

I'm using SWIG to call a C++ program from python with three arguments. The last argument is also being used for the return value.

analysis.i

%module coverage
%{
//#include "../SeqMCMC/src/funeval_base.hpp"
  #include "coverage.hpp"
%}

%include "std_vector.i"

void coverage(std::vector<double> *Pypar,  std::vector<std::vector<double> > *Pyxpass,   std::vector<std::vector<double> > *Pyypass);

coverage.hpp

#ifndef _COVERAGE_
#define _COVERAGE_
#include<vector>
void coverage(std::vector<double> *Pypar,
              std::vector<std::vector<double>> *Pyxpass,
              std::vector<std::vector<double>> *Pyypass);
#endif

coverage.cpp

#include "isofuneval.hpp"
#include "funeval_base.hpp"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp> 

void coverage (std::vector<double> *Pypar,
               std::vector<std::vector<double>> *Pyxpass,
               std::vector<std::vector<double>> *Pyypass){

  //Convert the par, xpass and ypass vectors as ublas
  boost::numeric::ublas::vector<double> par((*Pypar).size());
  boost::numeric::ublas::matrix<double> xpass((*Pyxpass).size(),(*Pyxpass)[0].size());
  boost::numeric::ublas::matrix<double> ypass((*Pyypass).size(),(*Pyypass)[0].size());

  for (size_t i = 0; i < (*Pypar).size(); i++){
    par(i) = (*Pypar)[i];
  }

  for (size_t i = 0; i < (*Pyxpass).size(); i++){
    for (size_t j = 0; j <(*Pyxpass)[0].size(); j++){
      xpass(i,j) = (*Pyxpass)[i][j] ;}
  }

  for (size_t i = 0; i < (*Pyypass).size(); i++){
    for (size_t j = 0; j <(*Pyypass)[0].size(); j++){
      ypass(i,j) = (*Pyypass)[i][j];}
  }

  isofuneval CoveragePlot;

  CoveragePlot.function(par, xpass, ypass); //These should actually be references and or pointers if I expect ypass to have the result

  for (size_t i = 0; i < (*Pyypass).size(); i++){
    for (size_t j = 0; j <(*Pyypass)[0].size(); j++){
      (*Pyypass)[i][j] = ypass(i,j) ;
    }
  }
}

It compiles, and the module loads, but when I run it:

import _coverage as     coverage
coverage.coverage([3, 2, 1 ],[[4, 8423] , [4, 12] ],[[24,234 ], [23, 23] ])

I get the following error:

TypeError: in method 'coverage', argument 1 of type 'std::vector< double,std::allocator< double > > *'

Upvotes: 1

Views: 800

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117876

In your analysis.i file declare your template specializations explicitly

%template(DoubleVector1D) std::vector<double>;
%template(DoubleVector2D) std::vector<std::vector<double>>;

Upvotes: 1

Related Questions