问题
I have an an array class, Array1D, defined in c++ which essentially wraps the STL vector class. I extended this class so that I can display individual elements of the array vector. Here is the relevant code in my SWIG interface file:
namespace std{
%template(dblVector) vector<double>;
}
%extend Array1D{
double __getitem__(int index) {
return (*self)[index];
}
}
This allows me to access individual elements of the array in python:
>>> a = Array1D(10) # creates a c++ vector of length 10 with zeros
>>> a[0]
>>> 0
I want to be able to call a[1:3]
for example, however, I get a TypeError when I try this:
TypeError: in method 'Array1D___getitem__', argument 2 of type 'int'
回答1:
The problem is that python passes a Slice object when calling the slice variant of the getitem and your function definition is expecting an int. You will need to write a version of getitem that takes PyObject* as a parameter and then you'd have to implement the slicing of the vector there.
I am writing this without being setup to actually test it, so take it with a grain of salt. But I would do something like the following.
%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 */
}
}
来源:https://stackoverflow.com/questions/23206796/how-to-get-python-slicing-to-work-with-my-c-array-class-using-swig