How To Get Python Slicing To Work With My C++ Array Class Using Swig
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.
Solution 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 */intlen = 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 */
}
}
Post a Comment for "How To Get Python Slicing To Work With My C++ Array Class Using Swig"