Re: Default argument for C++ shared_ptr in Python

William S Fulton <[email protected]>
Newsgroups gmane.comp.programming.swig
Message-ID <CANGqftC=D6WrK4pEyJH+FvojRxpARhqJiCH2kuybH6ChB=1B5w@mail.gmail.com>
On Thu, 13 Feb 2020 at 14:13, Michael Riesch <[email protected]> wrote:

> Hello all,
>
> First of all, thanks for your work on SWIG! Very useful tool!
>
> There is one issue, though: I am trying to build a Python interface for
> a C++ library with different classes. Now I would like to write a
> function with an optional argument of std::shared_ptr<device>, where
> device is one of those C++ classes. SWIG generates the interface code
> which compiles readily. And as long as I call the function with an
> argument (also if I provide "None") everything works. However, if I
> don't provide an argument, Python does not find the correct signature.
>
> SWIG 2.0.12 works fine, by the way. Apparently, the pointer support was
> revised in SWIG 3, which is where my troubles start.
>
> This behavior can be reproduced with the minimal (not) working example:
>
> test.hpp:
>
>      #include <iostream>
>      #include <memory>
>
>      class device {
>      public:
>       double number;
>      };
>
>      void my_func(std::shared_ptr<device> ptr = NULL) {
>
>        if (ptr != NULL) {
>
Above should be ptr == NULL.

         std::cout << "Pointer is NULL!" << std::endl;
>        } else {
>          std::cout << "Pointer is not NULL!" << std::endl;
>        }
>      }
>
> test.i:
>
>      %module test
>      %{
>      #include "test.hpp"
>      %}
>
>      %include "stl.i"
>      %include "std_shared_ptr.i"
>
>      %shared_ptr(device)
>
>      %include "test.hpp"
>
> Now SWIG >= 3.0.2 generates the interface code (by calling swig -c++
> -python test.i), where the generated test.py contains the crucial lines
>
>      def my_func(ptr=0):
>        return _test.my_func(ptr)
>      my_func = _test.my_func
>
> If I replace 0 with None, everything works fine. But in the original
> version it complains that there is no matching signature.
>
> This is a bug due to a change in optional argument handling where they are
by default obtained from Python rather than C++ code. Unfortunately this
won't be so easy to fix. Can you please raise a bug on Github? The
workaround is documented at
http://www.swig.org/Doc4.0/Python.html#Python_default_args to restore
obtaining the default argument from C++ code. You would add this before
SWIG parses my_func:

%feature("python:cdefaultargs") my_func;

William

_______________________________________________
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.