Default argument for C++ shared_ptr in Python

Michael Riesch <[email protected]>
Newsgroups gmane.comp.programming.swig
Message-ID <[email protected]>
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) {
         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.

Is this a bug or am I doing something wrong?

Thanks a lot in advance!

Best regards,
Michael
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.