title: ctypes: how to define a ctypes.Structure for a C struct that references itself?
body: <p>In C, it is allowed to define a struct that embeds pointers to objects of the same struct that is being defined. For example, the following <code>node</code> struct implementation for nodes of a list</p>
  
  <pre><code>typedef struct node{
      void *val;
      struct node *next;
      struct node *prev;
  } node;
  </code></pre>
  
  <p>embeds pointers <code>next</code> and <code>prev</code> that are of type <code>node*</code>.</p>
  
  <p>Translating this naïvely into a Python <code>ctypes.Structure</code> class yields:</p>
  
  <pre><code>class NODE(Structure):
      _fields_ = [ ("val", c_void_p),
                   ("next", POINTER(NODE)),
                   ("prev", POINTER(NODE)) ]
  </code></pre>
  
  <p>However, python does not allow to make reference to a class (in this example, <code>NODE</code>) within its own definition (<code>NameError: name 'NODE' is not defined</code>).</p>
  
  <p>How can I work around this?</p>
  
  <p>PS: I attempted defining the <code>_fields_</code> attribute <em>after</em> the class definition</p>
  
  <pre><code>class NODE(Structure):
      _fields_ = []
  NODE._fields_ = [ ("val", c_void_p),
                    ("next", POINTER(NODE)),
                    ("prev", POINTER(NODE)) ]
  </code></pre>
  
  <p>but this is not allowed because <code>_fields_</code> is tagged (?) as <code>final</code> in the ctypes.Structure base-class.  (<code>AttributeError: _fields_ is final</code>)</p>