Re: Raising Python exceptions from C code

William S Fulton <[email protected]>
Newsgroups gmane.comp.programming.swig
Message-ID <CANGqftBr70Husi5s1M7RjT4KBEGcvRV2vr+q2=66wmZ0bq5Grw@mail.gmail.com>
Hi Kevin

SWIG is wrapping C code where errors are not really expected in the target
language, SWIG usually expects some sort of C error handling and can deal
with that. Nevertheless, I think you can treat the setting of a Python
error as an equivalent C error setting mechanism and utilise %exception.
Here is a short example how:

%module example

%exception {
$action
if (PyErr_Occurred()) {
  printf("Failure!\n");
  SWIG_fail;
}
}
%inline %{
static int err = 0;
void * go(void) {
  PyErr_SetString(PyExc_RuntimeError, "Failed horribly");
  return NULL;
}
%}

This will generate code that will check for a Python error occurring
straight after the C function call and return straight away if one had.

William

On Wed, 8 Jul 2020 at 22:31, Kevin Smith <[email protected]>
wrote:

> I’m trying to figure out how I can raise a Python exception from a
> function in my .i file.  It’s fairly easy to call PyErr_SetString in the
> function, but the problem is that Python expects that when an exception
> occurs no value should be returned by the called function.  My function
> returns a pointer, but it’s NULL if an error occurs.  This NULL gets
> wrapped in a SWIG_NewPointerObj(SWIG_as_voidptr(result), … ) call and
> returned to Python which results in Python complaining about the returned
> value.  What I’d like to have happen in the wrapper is:
>
>    resultobj =  (!result && PyErr_Occurred()) ? NULL :
> SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_void, 0 |  0 );
>
> This way, if the result is NULL and a Python exception happened during the
> function, a NULL would be returned to make Python happy.
>
> Maybe there’s a better way to do what I’m attempting, but this was what I
> came up with.  I’m just not sure how to get this syntax into my wrappers
> without post-processing them.
>
> Kevin Smith
> [email protected]
>
>
>
>
>
>
> _______________________________________________
> Swig-user mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/swig-user
>

_______________________________________________
Swig-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/swig-user
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.