5

I tried to bind a static function which returns a shared_ptr pointed to another class.

Here is the sample code

class Example {
  public:
    Example() {}
    ~Example() {}
};

class ABC {
  public:
    static std::shared_ptr<Example> get_example() {std::make_shared<Example();}
 };

void init_abc(py::module & m) {
  py::class_<Example>(m, "Example")
    .def(py::init<>());

  py::class_<ABC>(m, "ABC")
    .def_static("get_example", &ABC::get_example);
}

Here is the python side

example = my_module.ABC.get_example()

However, python side threw a segmentation fault.

Any idea?

alec.tu
  • 1,647
  • 2
  • 20
  • 41
  • I don't know if pybind11 support `shared_ptr` or not, if not, you can always try to return the actual pointer using `.get()`. It doesn't necessarily matter if you return a `shared_ptr` or the actual `pointer` when you are at Python side, because `shared_ptr` is managed by C++ anyway. I think it should be safe to use `.get()` if that resolve the issue. – Amir May 07 '19 at 08:22

1 Answers1

3

There are some missing bits in your code like >. Here is working example:

class Example {
public:
    Example() {}
    ~Example() {}
};

class ABC {
public:
    static std::shared_ptr<Example> get_example() { return std::make_shared<Example>();}
};

Next, provide additional template argument shared_ptr<Example> in place where you wrap Example class:

py::class_<Example, std::shared_ptr<Example>>(m, "Example")
    .def(py::init<>());

py::class_<ABC>(m, "ABC")
    .def_static("get_example", &ABC::get_example);

This way shared_ptr<Example> will be handled properly.

Piotr Barejko
  • 608
  • 4
  • 15