Python swig包装的向量的向量的双显示为元组

Python swig-wrapped vector of vector of doubles appears as Tuple

本文关键字:向量 元组 双显示 swig Python 包装      更新时间:2023-10-16

我在C++中有一个函数,它返回一个vector<vector<double> >对象。我已经使用Swig为Python包装了它。当我调用它时,我无法随后使用resize()push_back()矢量方法修改函数的输出。

当我尝试此操作时,我得到一个错误,即"tuple"对象没有属性"resize"或"push_back"。当我在Python中与向量交互时,Swig是否会将向量转换为元组对象?如果是这样的话,那么我假设Python中这个函数的输出是不可变的,这是一个问题。我可以将这个对象传递到接受双向量的向量的包装方法中。我只是不能使用Python中的向量方法来处理它。任何关于为什么会这样的解释或解决方案的想法都将不胜感激。

这是我的swig文件供参考。STL模板行即将结束:

/* SolutionCombiner.i */
%module SolutionCombiner
%{
    /* Put header files here or function declarations like below */
    #include "Coord.hpp"
    #include "MaterialData.hpp"
    #include "FailureCriterion.hpp"
    #include "QuadPointData.hpp"
    #include "ModelSolution.hpp"
    #include "ExclusionZone.hpp"
    #include "CriticalLocation.hpp"
    #include "FailureMode.hpp"
    #include "ExecutiveFunctions.hpp"
    #include <fstream>
    #include <iostream> 
%}
%{
    #define SWIG_FILE_WITH_INIT
    std::ostream& new_ofstream(const char* FileName){
        return *(new std::ofstream(FileName));
    }
    std::istream& new_ifstream(const char* FileName){
        return *(new std::ifstream(FileName));
    }
    void write(std::ostream* FOUT, char* OutString){
        *FOUT << OutString;
    }
    std::ostream *get_cout(){return &std::cout;}
%}
%include "std_vector.i"
%include "std_string.i"
%include "std_set.i"
%include "../../source/Coord.hpp"
%include "../../source/MaterialData.hpp"
%include "../../source/FailureCriterion.hpp"
%include "../../source/QuadPointData.hpp"
%include "../../source/ModelSolution.hpp"
%include "../../source/ExclusionZone.hpp"
%include "../../source/CriticalLocation.hpp"
%include "../../source/FailureMode.hpp"
%include "../../source/ExecutiveFunctions.hpp"
namespace std {
   %template(IntVector) vector<int>;
   %template(DoubleVector) vector<double>;
   %template(DoubleVVector) vector<vector<double> >;
   %template(DoubleVVVector) vector<vector<vector<double> > >;
   %template(SolutionVector) vector<ModelSolution>;
   %template(CritLocVector) vector<CriticalLocation>;
   %template(CritLocVVector) vector<vector<CriticalLocation> >;
   %template(ModeVector) vector<FailureMode>;
   %template(IntSet) set<int>;
}
std::ofstream& new_ofstream(char* FileName);
std::ifstream& new_ifstream(char* FileName);
std::iostream *get_cout();

是的,向量模板返回一个不可变的Python元组。也许您可以修改std_vector.i实现以返回列表,但这可能是有充分理由的。您可以将它们转换为列表,以便在Python:中操作它们

>>> x.func()
((1.5, 2.5, 3.5), (1.5, 2.5, 3.5), (1.5, 2.5, 3.5), (1.5, 2.5, 3.5))
>>> [list(n) for n in x.func()]
[[1.5, 2.5, 3.5], [1.5, 2.5, 3.5], [1.5, 2.5, 3.5], [1.5, 2.5, 3.5]]  

注意:我制作了一个返回vector<vector<double>>作为测试的示例函数。