双向矢量的Python swig包裹的矢量出现作为元组

时间:2012-03-07 02:30:56

标签: c++ python stl swig stdvector

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

当我尝试这个时,我得到一个错误,即'tuple'对象没有属性'resize'或'push_back'。当我在Python中与它们交互时,Swig是否将向量转换为Tuple对象?如果是这种情况,那么我假设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();

1 个答案:

答案 0 :(得分:1)

是的,矢量模板返回一个不可变的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>>作为测试。