From: Ben W. <be...@sa...> - 2006-08-18 18:42:40
|
Eliot Blennerhassett wrote: > I am again trying to add Python exceptions to a C library. > > All but one or two functions return an error code, which I want to > convert to an exception. > > So i have this code. > > // convert HPI error return into Python exception > %exception { > // Exception handler from hpi.i > $action > if (result) { > PyErr_Format(PyExc_Exception,"HPI error %d",result); > return NULL; > } > } > > %typemap(out) return_type { > // Empty out typemap discards function return value > // either get exception, or return value is zero! > } > > > However, there are also a few structs in the interface, and the > exception handling code above gets inserted into wrap_delete_MYSTRUCT() > function in the wrapper code. Problem is that there is no "result" > variable in this function. We don't use the %exception handler for our C library, which consists of functions of the form void foo(..., int *ierr); where the final argument 'ierr' is filled in with 0 on success, non-zero on error. This is handled with the following two typemaps: %typemap(in, numinputs=0) int *ierr (int temp) { $1 = &temp; } %typemap(argout) int *ierr { if (*$1 != 0) { PyErr_Format(PyExc_Exception, "Generic error %d", *$1); #ifdef SWIGPYTHON Py_DECREF(resultobj); #endif SWIG_fail; } } This avoids unnecessary wrapping of functions which don't return an 'ierr' status, but needs to do a little bit of extra cleanup to avoid C (SWIG_fail) and Python (Py_DECREF) memory leaks. Ben -- be...@sa... http://salilab.org/~ben/ "It is a capital mistake to theorize before one has data." - Sir Arthur Conan Doyle |