title: How do I use SWIG to return specific exceptions based on C function return type?
body: <p>Here are examples of functions in my C API:</p>
  
  <pre><code>int do_something(struct object *with_this)
  struct object *get_something(struct object *from_this)
  </code></pre>
  
  <p><code>do_something</code> will return <code>0</code> for success or <code>-1</code> and set <code>errno</code> for failure. <code>get_something</code> will return a valid pointer on success or <code>NULL</code> and set <code>errno</code> for failure.</p>
  
  <p>I'm using to SWIG 2.0 to generate python bindings. For the <code>do_something</code> binding I'd like it to return an exception based on <code>errno</code> if it fails and return the Python <code>None</code> object if it succeeds. For the <code>get_something</code> binding I'd like it to return an exception based on <code>errno</code> if it fails and the opaque object if it succeeds.</p>
  
  <p>The question is how do I get SWIG to do all of this magic for me?</p>
  
  <p>Currently I'm using SWIG 2.0.</p>
  
  <p>I can use <code>%exception</code> and define different exceptions per symbol, but I'd like it to be based on return type. I'll have a lot of the API functions and I don't want to list them out. So I can do this for each symbol:</p>
  
  <pre><code>%exception do_something {
      $action
      if (result &lt; 0) {
          return PyErr_SetFromErrno(PyExc_RuntimeError);
      }
  }
  
  %exception get_something {
      $action
      if (result == NULL) {
          return PyErr_SetFromErrno(PyExc_RuntimeError);
      }
  }
  </code></pre>
  
  <p>It would be a lot better if I could do something like this (like you can do with <code>%typemap</code>):</p>
  
  <pre><code>%exception int {
      $action
      if (result &lt; 0) {
          return PyErr_SetFromErrno(PyExc_RuntimeError);
      }
  }
  
  %exception struct object * {
      $action
      if (result == NULL) {
          return PyErr_SetFromErrno(PyExc_RuntimeError);
      }
  }
  </code></pre>
  
  <p>Can I do something like this? If I had something like this, then that would take care of the exceptions. And I believe my <code>get_something</code> binding would be perfect.</p>
  
  <p>My <code>do_something</code> binding would still need something like this to get it to return the Python None object if I use <code>%typemap</code>:</p>
  
  <pre><code>%typemap(out) int {
      $result = Py_BuildValue("");
  }
  </code></pre>
  
  <p>Does the magic I'm looking for exist or am I going about this all wrong? Is there a better way to do this?</p>