Automatic conversion between C++ types with `pybind11`

Viewed 43

I'm trying to understand if it is possible to automatically convert types using C++ automatic conversions when passing arguments to functions exposed by pybind11.

For example:

#include <pybind11/pybind11.h>

namespace py = pybind11;

struct S1 {
  S1(int _x) : x{_x} { }
  int x;
};

struct S2 {
  S2(S1 s1) : y{s1.x} { }
  int y;
};

static
int func(S2 s) { return s.y; }

PYBIND11_MODULE(my_module, m) {
  py::class_<S1>(m, "S1")
    .def(py::init<int>());
  py::class_<S2>(m, "S2")
    .def(py::init<S1>());

  m.def("func", &func);
}

Now, on the Python side:

>>> from my_module import *
>>> s = S1(42)
>>> func(S2(s))
42
>>> func(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func(): incompatible function arguments. The following argument types are supported:
    1. (arg0: my_module.S2) -> int

Invoked with: <my_module.S1 object at 0x1051ef470>

So I can explicitly construct an S2 from an S1 using the constructor, but it is not used when calling a function. Is there a way to make the conversion happen automatically on the Python side? Is this even possible? I mean, of course, without adding another overload of func() explicitly taking an S1.

0 Answers
Related