【问题标题】:SWIG: Passing a std::vector< std::vector <double> > pointer to pythonSWIG:将 std::vector< std::vector <double> > 指针传递给 python
【发布时间】:2018-05-04 16:00:17
【问题描述】:

我正在使用 SWIG 从 python 调用具有三个参数的 C++ 程序。最后一个参数也用于返回值。

分析.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) ;
    }
  }
}

它编译,模块加载,但是当我运行它时:

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

我收到以下错误:

TypeError:在方法“coverage”中,参数 1 类型为“std::vector > *”

【问题讨论】:

  • @CoryKramer,你有没有想过这个问题?我遇到了类似的问题?
  • @KartikAyyar 你试过我在下面发布的解决方案了吗?

标签: python c++ swig


【解决方案1】:

在您的 analysis.i 文件中明确声明您的模板特化

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

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多