繁体   English   中英

如何使用swig在operator []中扩展python中的c ++类

[英]How to extend c++ class in python with operator [], using swig

我有一个简单的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界面文件看起来像

 %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个,并输入[1]我得到TypeError: 'Array1D' object does not support indexing

我的SWIG接口文件应如何查看以扩展操作符方法,以便我可以在python中正确输出[1]? 我也想做一些像[1] = 3.0;

我想到了。 这是我需要添加到我的界面文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM