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

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

by wsfulton :: Rate this Message:

Reply to Author | View in Thread

Josh Cherry wrote:

>
> On Sun, 5 Jul 2009, Bo Peng wrote:
>
>> 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".
>
> My understanding/recollection is that None is acceptable for any pointer
> type (and is converted to a null pointer), but is not acceptable for a
> reference (which makes sense).  I'm not clear on the details of what
> you're doing, but that would appear to be the cause of that error message.
> This behavior is dictated by the standard typemaps for pointers and
> references.
>
Indeed and the typemaps showing the difference with the extra check (for
!argp) are in swigtype.swg and the preprocessed versions are shown below:

%typemap(in, noblock=1) SWIGTYPE *(void  *argp = 0, int res = 0) {
   res = SWIG_ConvertPtr($input, &argp,$descriptor, $disown |  0 );
   if (!SWIG_IsOK(res)) {
     SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname"
"', argument " "$argnum"" of type '" "$type""'");
   }
   $1 = reinterpret_cast< $ltype >(argp);
}

%typemap(in, noblock=1) SWIGTYPE & (void *argp = 0, int res = 0) {
   res = SWIG_ConvertPtr($input, &argp, $descriptor,  0 );
   if (!SWIG_IsOK(res)) {
     SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname"
"', argument " "$argnum"" of type '" "$type""'");
   }
   if (!argp) { SWIG_exception_fail(SWIG_ValueError, "invalid null
reference " "in method '" "$symname" "', argument " "$argnum"" of type
'" "$type""'"); }
   $1 = reinterpret_cast< $ltype >(argp);
}

William

------------------------------------------------------------------------------
Enter the BlackBerry Developer Challenge  
This is your chance to win up to $100,000 in prizes! For a limited time,
vendors submitting new applications to BlackBerry App World(TM) will have
the opportunity to enter the BlackBerry Developer Challenge. See full prize
details at: http://p.sf.net/sfu/blackberry
_______________________________________________
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.