如何使用swig用操作符[]扩展python中的c++类

2024-04-19 20:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的test.h文件和我自己的数组类(使用标准向量类):

#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接口文件看起来像

^{pr2}$

当我创建模块时,一切正常,但是当我实例化Array1D的对象时,a=测试阵列1d(10,2),它创建一个长度为10的向量,每个元素中有2个,然后输入a[1]得到 TypeError: 'Array1D' object does not support indexing。在

为了扩展operator方法以便在python中正确地输出[1],SWIG接口文件应该如何?我也希望能做一些事情,比如a[1]=3.0


Tags: 文件testdatareturninclude向量operatorswig