[Numpy-discussion] SWIG, numpy.i and errno: comments?

Egor Zindy ezindy@gmail....
Sun Aug 9 05:17:38 CDT 2009


Hello list,

this is my attempt at generating python exceptions in SWIG/C using the
errno mechanism:
http://www.scipy.org/Cookbook/SWIG_NumPy_examples#head-10f49a0f5ea6b313127d2ec5ffa1eaf1c133cb22

Used together with numpy.i, this has been useful for notifying (in a
pythonic way) memory allocation errors or array index problems.

A change in the errno global variable is detected in the %exception
part of the SWIG interface file, and Python exceptions are generated
after $action depending on the errno error code value.

%exception
{
    errno = 0;
    $action

    if (errno != 0)
    {
        switch(errno)
        {
            case EPERM:
                PyErr_Format(PyExc_IndexError, "Index out of range");
                break;
            case ENOMEM:
                PyErr_Format(PyExc_MemoryError, "Failed malloc()");
                break;
            default:
                PyErr_Format(PyExc_Exception, "Unknown exception");
        }
        return NULL;
    }
}

If there's a better way of doing this, I'll update the cookbook recipe.

Regards,
Egor


More information about the NumPy-Discussion mailing list