2012-03-07 59 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>>作爲測試樣本功能。