« Return to Thread: Accepting None as a valid input for the constructor of a C++ class.

Accepting None as a valid input for the constructor of a C++ class.

by Bo Peng-2 :: Rate this Message:

Reply to Author | View in Thread

Dear swig users,

I have a C++ class that is wrapped into a Python shadow class. In
addition to regular Python input (say, a number),  I would like to
allow users to pass None from the user interface and tells the C++
class no invalid input is given. It is more or less like using -1 as a
default parameter when only positive numbers are allowed.

However, SWIG does not seem to allow such usage because it will not
pass None to the C++ class even if it accepts such an input (e.g. with
a constructor that accepts a PyObject * object). Whenever I pass None,
I would get an error message such as "Invalid null reference".

When I read the wrapper file, I find the following piece of code:

  if (obj5) {
    res6 = SWIG_ConvertPtr(obj5, &argp6, SWIGTYPE_p_simuPOP__uintList,
 0  | SWIG_POINTER_IMPLICIT_CONV);
    if (!SWIG_IsOK(res6)) {
      SWIG_exception_fail(SWIG_ArgError(res6), "in method '"
"new_stat" "', argument " "6"" of type '" "simuPOP::uintList const
&""'");
    }
    if (!argp6) {
      SWIG_exception_fail(SWIG_ValueError, "invalid null reference "
"in method '" "new_stat" "', argument " "6"" of type '"
"simuPOP::uintList const &""'");
    }
    arg6 = reinterpret_cast< simuPOP::uintList * >(argp6);
  }

The problem is that when SWIG_ConvertPtr is called

SWIGRUNTIME int
SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info
*ty, int flags, int *own) {
  if (!obj) return SWIG_ERROR;
  if (obj == Py_None) {
    if (ptr) *ptr = 0;
    return SWIG_OK;
  } else {


It treats Py_None directly as a special case and does not call the
implicit constructor at all.

Is there a way to get around this problem?? I guess what I need is
that SWIG passes Py_None to the constructor when flag
SWIG_POINTER_IMPLICIT_CONV is set to true.

Many thanks in advance.
Bo

------------------------------------------------------------------------------
_______________________________________________
Swig-user mailing list
Swig-user@...
https://lists.sourceforge.net/lists/listinfo/swig-user

 « Return to Thread: Accepting None as a valid input for the constructor of a C++ class.