I have written a Python extension for a C library. I have a data structure that looks like this:
typedef struct _mystruct{
double * clientdata;
size_t
I encountered the very same problem with Python 2.6, and solved it thank to @aphex reply. But I wanted to avoid any magic value, or extra boolean to pass end-of-list condition. Sure enough, my iterator have an atEnd() methods that tells me I am past the end of the list.
So in fact, it is fairly easy with SWIG exception handling. I just had to add the following magic:
%ignore MyStructIter::atEnd();
%exception MyStructIter::next {
if( $self->list->atEnd() ) {
PyErr_SetString(PyExc_StopIteration,"End of list");
SWIG_fail;
}
$action
}
The point is this snipet skips the next() calls completly once you are past the end of list.
If you stick to your idioms, it should look like:
%exception MyStructIter::next {
if( $self->pos >= $self->list->len ) {
PyErr_SetString(PyExc_StopIteration,"End of list");
SWIG_fail;
}
$action
}
NOTE FOR PYTHON 3.x:
You shall name your next() function with the magic "__ " prefix&postfix name. One option is simply to add:
%rename(__next__) MyStructIter::next;