From 6f691eb7d87f272ca17eb4bf25b44280742cd254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Wed, 26 Feb 2020 00:00:02 +0000 Subject: [PATCH] pybind11 example: add inheritance --- userland/libs/pybind11/class_test.cpp | 13 ++++++++++++- userland/libs/pybind11/class_test_main.py | 12 +++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/userland/libs/pybind11/class_test.cpp b/userland/libs/pybind11/class_test.cpp index 98717ea..0f86c19 100644 --- a/userland/libs/pybind11/class_test.cpp +++ b/userland/libs/pybind11/class_test.cpp @@ -3,12 +3,19 @@ #include struct ClassTest { - ClassTest(const std::string &name) : name(name) { } + ClassTest(const std::string &name) : name(name) {} void setName(const std::string &name_) { name = name_; } const std::string &getName() const { return name; } std::string name; }; +struct ClassTestDerived : ClassTest { + ClassTestDerived(const std::string &name, const std::string &name2) : + ClassTest(name), name2(name2) {} + std::string getName2() { return name + name2 + "2"; } + std::string name2; +}; + namespace py = pybind11; PYBIND11_PLUGIN(class_test) { @@ -18,5 +25,9 @@ PYBIND11_PLUGIN(class_test) { .def("setName", &ClassTest::setName) .def("getName", &ClassTest::getName) .def_readwrite("name", &ClassTest::name); + py::class_(m, "ClassTestDerived") + .def(py::init()) + .def("getName2", &ClassTestDerived::getName2) + .def_readwrite("name", &ClassTestDerived::name); return m.ptr(); } diff --git a/userland/libs/pybind11/class_test_main.py b/userland/libs/pybind11/class_test_main.py index adba727..41510a0 100755 --- a/userland/libs/pybind11/class_test_main.py +++ b/userland/libs/pybind11/class_test_main.py @@ -2,8 +2,10 @@ import class_test -my_class_test = class_test.ClassTest("abc"); -print(my_class_test.getName()) -my_class_test.setName("012") -print(my_class_test.getName()) -assert(my_class_test.getName() == my_class_test.name) +my_class_test = class_test.ClassTest('abc'); +assert(my_class_test.getName() == 'abc') +my_class_test.setName('012') +assert(my_class_test.name == '012') + +my_class_test_derived = class_test.ClassTestDerived('abc', 'def'); +assert(my_class_test_derived.getName2() == 'abcdef2')