Demonstrating that py::cast<std::unique_ptr<Foo>>(foo_py); works with py::classh…

Demonstrating that py::cast<std::unique_ptr<Foo>>(foo_py); works with py::classh (it does not build with class_).
parent 9cca45a0
...@@ -15,23 +15,28 @@ public: ...@@ -15,23 +15,28 @@ public:
int bar(int i) { return num + i; } int bar(int i) { return num + i; }
}; };
using FooFactory = std::function<Foo()>; } // namespace open_spiel_pattern
} // namespace pybind11_tests
int MakeAndUseFoo(FooFactory f) { PYBIND11_SMART_HOLDER_TYPE_CASTERS(pybind11_tests::open_spiel_pattern::Foo)
auto foo = f();
return foo.bar(456); namespace pybind11_tests {
namespace open_spiel_pattern {
int RecycleFoo() {
Foo foo_orig(123);
py::object foo_py = py::cast(foo_orig);
auto foo_from_py = py::cast<std::unique_ptr<Foo>>(foo_py);
return foo_from_py->bar(456);
} }
} // namespace open_spiel_pattern } // namespace open_spiel_pattern
} // namespace pybind11_tests } // namespace pybind11_tests
// To use py::smart_holder, uncomment the next line and change py::class_ below to py::classh.
// PYBIND11_SMART_HOLDER_TYPE_CASTERS(pybind11_tests::open_spiel_pattern::Foo)
TEST_SUBMODULE(open_spiel_pattern, m) { TEST_SUBMODULE(open_spiel_pattern, m) {
using namespace pybind11_tests::open_spiel_pattern; using namespace pybind11_tests::open_spiel_pattern;
py::class_<Foo>(m, "Foo").def(py::init<int>()).def("bar", &Foo::bar); py::classh<Foo>(m, "Foo");
m.def("make_and_use_foo", MakeAndUseFoo); m.def("recycle_foo", RecycleFoo);
} }
...@@ -3,6 +3,7 @@ import pytest ...@@ -3,6 +3,7 @@ import pytest
from pybind11_tests import open_spiel_pattern as m from pybind11_tests import open_spiel_pattern as m
def test_make_and_use_foo():
res = m.make_and_use_foo(lambda : m.Foo(123)) def test_recycle_foo():
res = m.recycle_foo()
assert res == 579 assert res == 579
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment