2012-03-07 83 views
1

我有一个C++函数,它返回vector<vector<double> >对象。我已经使用Swig将它包装为Python。当我打电话时,我无法使用resize()push_back()矢量方法修改函数的输出。Python swig-wrapped矢量双精度矢量显示为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

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