Last active
May 12, 2020 11:46
-
-
Save cvanelteren/170a2fada359f2642715a78a2595d60d to your computer and use it in GitHub Desktop.
Binding nested subclasses in pybind11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pybind11/stl.h> | |
#include <pybind11/pybind11.h> | |
#include <pybind11/operators.h> | |
namespace py = pybind11; | |
using namespace pybind11::literals; | |
using namespace std; | |
template<typename T> | |
class Property{ | |
public: | |
virtual ~Property(){} | |
virtual Property& operator= (const T& f){ value = f; return *this;} | |
virtual const T& operator () () const {return value;} | |
virtual explicit operator const T& () const {return value;} | |
virtual T* operator->() {return &value;} | |
protected: | |
T value; | |
}; | |
class Test { | |
public: | |
Test() { someProperty = 1.; } | |
class NestedProperty: public Property<float>{ | |
public: | |
virtual NestedProperty& operator= (const double &f){ | |
value = f; return *this; | |
} | |
}; | |
NestedProperty someProperty; | |
}; | |
PYBIND11_MODULE(example, m) { | |
py::class_<Test>(m, "Test") | |
.def(py::init<>()) | |
.def_property("someProperty", | |
[](const Test &self) { return static_cast<float>(self.someProperty); }, | |
[](Test &self, float value) { self.someProperty = value; }); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for @YannickJadoul for providing the cpp code.