SWIG interfacing C library to Python (Creating 'iterable' Python data type from C 'sequence' struct)

后端 未结 4 1280
北海茫月
北海茫月 2020-12-01 15:17

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          


        
4条回答
  •  攒了一身酷
    2020-12-01 15:46

    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;
    

提交回复
热议问题