如何使用SWIG在Python中扩展C++类并重载[]运算符

4 投票
1 回答
1228 浏览
提问于 2025-04-18 00:28

我有一个简单的 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,然后我尝试访问 a[1] 时,出现了 TypeError: 'Array1D' object does not support indexing 的错误。

我的 SWIG 接口文件应该怎么写,才能扩展这个操作符的方法,让我可以在 Python 中正确输出 a[1]?我还想能像这样做 a[1] = 3.0;

1 个回答

6

我搞明白了。我需要在我的接口文件中添加这个:

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

撰写回答