2014-03-29 30 views
2

我有一個與自己的陣列類的簡單test.h文件(它使用標準的矢量類):如何在python擴展的C++類與操作符[],使用痛飲

#include <vector> 
#include <string> 

using namespace std; 

class Array1D{ 
private: 
    vector<double> data_; 
    int xsize_; 
public: 
    Array1D(): xsize_(0) {}; 

    // creates vector of size nx and sets each element to t 
    Array1D(const int& nx, const double& t): xsize_(nx) { 
     data_.resize(xsize_, t); 
    } 

    double& operator()(int i) {return data_[i];} 
    const double& operator[](int i) const {return data_[i];} 

}; 

我想成爲能夠在使用swig的python中使用[]運算符。我的當前SWIG接口文件看起來像

%module test 

%{ 
#define SWIG_FILE_WITH_INIT 
#include "test.h" 
%} 

%include "std_vector.i" 

namespace std{ 
%template(DoubleVector) vector<double>; 
} 

%include "test.h" 

當我使模塊,一切都正常運行,但是當我實例Array1D中,a = test.Array1D(10,2),它創建了一個長度爲10向量的一個目的在每個元素中有2個,並鍵入a [1]我得到 TypeError: 'Array1D' object does not support indexing

我的SWIG接口文件應該如何查找以擴展操作符方法,以便我可以在python中正確輸出[1]?我也想能夠做一些[1] = 3.0;

+0

如果你想分配給它 – Julius

+2

你不應該返回一個常量裁判這不是一個重複http://stackoverflow.com/questions/22736700 /如何對延伸-A-模板-c級合蟒與 - 痛飲到允許最操作? – Schollii

回答

5

我想通了。這正是我需要添加到我的接口文件:

%extend Array1D{ 
    const double& __getitem__(int i) { 
     return (*self)[i]; 
    } 
}