title: SWIG interfacing C library to Python (Creating 'iterable' Python data type from C 'sequence' struct)
body: <p>I have written a Python extension for a C library. I have a data structure that looks like this:</p>
  
  <pre><code>typedef struct _mystruct{
     double * clientdata;
     size_t   len;
  } MyStruct;
  </code></pre>
  
  <p>The purpose of this datatype maps directly to the list data type in Python. I therefore, want to create 'list-like' behavior for the exported struct, so that code written using my C extension is more 'Pythonic'.</p>
  
  <p>In particular, this is what I want to be able to do (from python code)
  Note: py_ctsruct is a ctsruct datatype being accessed in python.</p>
  
  <p>My requirements can be sumarized as:</p>
  
  <ol>
  <li>list(py_ctsruct) returns a python list with all contents copied out from the c struct</li>
  <li>py_cstruct[i] returns <strong><em>ith</em></strong> element (preferably throws IndexError on invalid index)</li>
  <li>for elem in py_ctsruct: ability to enumerate </li>
  </ol>
  
  <p>According to <a href="http://www.python.org/dev/peps/pep-0234/" rel="noreferrer">PEP234</a>, <strong>An object can be iterated over with "for" if it implements
     _<em>iter</em>_() or _<em>getitem</em>_()</strong>. Using that logic then, I think that by adding the following attributes (via <a href="http://www.swig.org/Doc1.3/SWIG.html#SWIG_rename_ignore" rel="noreferrer">rename</a>) to my SWIG interface file, I will have the desired behavior (apart from req. #1 above - which I still dont know how to achieve):</p>
  
  <pre><code>__len__
  __getitem__
  __setitem__
  </code></pre>
  
  <p>I am now able to index the C object in python. I have not yet implemented the Python exception throwing, however if array bounds are exceeded, are return a magic number (error code).</p>
  
  <p>The interesting thing is that when I attempt to iterate over the struct using 'for x in' syntax for example:</p>
  
  <pre><code>for i in py_cstruct:
      print i
  </code></pre>
  
  <p>Python enters into an infinite loop that simply prints the magic (error) number mentioned above, on the console. which suggests to me that there is something wrong with the indexing.</p>
  
  <p>last but not the least, how can I implement requirement 1? this involves (as I understand it):</p>
  
  <ul>
  <li>handling' the function call <strong>list()</strong> from python</li>
  <li>Returning a Python (list) data type from C code</li>
  </ul>
  
  <p><strong>[[Update]]</strong></p>
  
  <p>I would be interested in seeing a little code snippet on what (if any) declarations I need to put in my interface file, so that I can iterate over the elements of the c struct, from Python.</p>