如何使用SWIG使Python切片与我的C++数组类一起工作
我有一个数组类,叫做Array1D,是用C++写的,主要是为了封装STL的向量类。我对这个类进行了扩展,这样我就可以显示数组向量中的单个元素。下面是我在SWIG接口文件中的相关代码:
namespace std{
%template(dblVector) vector<double>;
}
%extend Array1D{
double __getitem__(int index) {
return (*self)[index];
}
}
这段代码让我可以在Python中访问数组的单个元素:
>>> a = Array1D(10) # creates a c++ vector of length 10 with zeros
>>> a[0]
>>> 0
我想要能够像这样调用 a[1:3]
,但是当我尝试这样做时,出现了一个类型错误:
TypeError: in method 'Array1D___getitem__', argument 2 of type 'int'
1 个回答
1
问题在于,当调用切片版本的getitem时,Python会传递一个切片对象,而你的函数定义却是期待一个整数。你需要写一个接受PyObject*作为参数的getitem版本,然后在里面实现对向量的切片操作。
我写这个的时候并没有实际测试环境,所以请谨慎对待。不过我会做类似下面这样的事情。
%extend Array1D
{
Array1D* __getitem__(PyObject *param)
{
if (PySlice_Check(param))
{
/* Py_ssize_t might be needed here instead of ints */
int len = 0, start = 0, stop = 0, step = 0, slicelength = 0;
len = this->size(); /* Or however you get the size of a vector */
PySlice_GetIndicesEx((PySliceObject*)param, len, &start, &stop, &step, &slicelength);
/* Here do stuff in order to return an Array1D that is the proper slice
given the start/stop/step defined above */
}
/* Unexpected parameter, probably should throw an exception here */
}
}