Re: don't return a return value that is really an error code

William S Fulton <[email protected]> Fri, 19 May 2023 07:59:56 +0100
Newsgroups gmane.comp.programming.swig
Message-ID <CANGqftBr1AOke8nWAsKMta6byQRhTgVRavXZyuVrirZKT5KVbw@mail.gmail.com>
I suggest writing a custom out typemap for your error code type (int ???)
and stop using %exception. Something along the lines of

%typemap(out,noblock=1,fragment="SWIG_From_int") int {
  if ($1 == 0) {
    // $result = SWIG_From_int((int)($1)); // This is the default typemap
for int
    $result = SWIG_Py_Void();
  } else {
    PyErr_SetString(PyExc_RuntimeError, "an error has occurred"); // will
replace with something more descriptive
    SWIG_fail;
  }
}

which returns None (void) on success otherwise throws an exception.

William


On Fri, 5 May 2023 at 23:07, Montare, Aidan A. (Fed) via Swig-user <
[email protected]> wrote:

> Hi! I’m wrapping a library where most of the functions follow the
> convention of returning an error code or 0 if no error. I’ve followed swig
> instructions to write an exception handler:
>
>
>
> %exception {
>
>     $action
>
>     if (result != 0) {
>
>         PyErr_SetString(PyExc_RuntimeError, "an error has occurred"); //
> will replace with something more descriptive
>
>         SWIG_fail;
>
>     }
>
> }
>
>
>
> Since errors are now translated into python exceptions,  I think if the
> function does succeed, I’d like to not return the error code 0. Many of the
> functions return via a parameter, and I think writing
>
>
>
> result = foo(arg)
>
>
>
> would be cleaner than having to write
>
>
>
> _, result = foo(arg)
>
>
>
> all over the place.
>
>
>
> How can I tell swig that the error code should not be return the error
> code?
>
>
>
> Best wishes,
>
>
>
> Aidan Montare (she/her)
>
> Time Realization and Distribution Group
>
> Time and Frequency Division
>
> NIST Boulder
>
>
>
>
> _______________________________________________
> 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