0

I use swig to generate Python binding for my C++ library. I want to export a method which returns a number and a numpy array. It is very easy to generate wrapper code.

%apply (uint8_t** ARGOUTVIEWM_ARRAY3, int* DIM1, int* DIM2, int* DIM3) {(uint8_t** frame, int *dim1, int *dim2, int *dim3)}

int get_frame(uint8_t** frame, int *dim1, int *dim2, int *dim3);

However, get_frame() will set frame pointer to NULL in some cases, and I want to Python method will return None instead of a numpy array. Currently, the generated code will raise a system error if frame is NULL.
My solution is to insert some lines of code in generated function _wrap_get_frame.

if (*arg1 == NULL)
{
    Py_INCREF(Py_None);
    resultobj = SWIG_Python_AppendOutput(resultobj, Py_None);
    return resultobj;
}

I have tested this new function, it works.
How can I ask swig to do this change automatically ?
Thanks !

shang12
  • 423
  • 5
  • 18
  • 1
    You could wrap your `get_frame` function into `checked_get_frame`, import that into SWIG and `%rename` it to `get_frame`. I wrote a similar answer here: https://stackoverflow.com/a/52051100 – Henri Menke Aug 21 '19 at 21:17

1 Answers1

0

Everybody can check the comment of Henri Menke. This is my solution:

I add an exception handler to insert my code below function call.

%exception get_frame {
  errno = 0;
  $action
  if (errno != 0)
  {
     resultobj = SWIG_From_int((int)(result));
     Py_INCREF(Py_None);
     resultobj = SWIG_Python_AppendOutput(resultobj, Py_None);
     return resultobj;
  }
}

Using variable resultobj from generated code is not general solution but it works with my SWIG 4.0.

shang12
  • 423
  • 5
  • 18