Type checking inside a C extension... doesn't throw exception on failure

Andrew MacIntyre andymac at bullseye.apana.org.au
Tue Apr 6 07:46:25 EDT 2004


On Tue, 6 Apr 2004, Jon Perez wrote:

>    // PyString_AsString(strobj);  // raises exception
>    strcpy(strstr,PyString_AsString(strobj));  /* crashes!! */
>
>    Py_INCREF(Py_None);
>    return Py_None;
> }
>
> What gives? Shouldn't the exception be raised within PyString_AsString()
> before it even gets a chance to return a value to strcpy()?

First rule of using the Python C API: _always_ check the return value of
API functions.

In the case you exhibit, if the return value of PyString_AsString is NULL,
a TypeError exception will have been set and you should immediately
return NULL.

When the interpreter gets a NULL return from a called function, it checks
for an exception.  If you don't return NULL, it can't detect the exception
until some other unrelated event turns it up.

--
Andrew I MacIntyre                     "These thoughts are mine alone..."
E-mail: andymac at bullseye.apana.org.au  (pref) | Snail: PO Box 370
        andymac at pcug.org.au             (alt) |        Belconnen  ACT  2616
Web:    http://www.andymac.org/               |        Australia




More information about the Python-list mailing list