Skip to content

Instantly share code, notes, and snippets.

@cvanelteren
Last active May 12, 2020 11:46
Show Gist options
  • Save cvanelteren/170a2fada359f2642715a78a2595d60d to your computer and use it in GitHub Desktop.
Save cvanelteren/170a2fada359f2642715a78a2595d60d to your computer and use it in GitHub Desktop.
Binding nested subclasses in pybind11
#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; });
}
@cvanelteren
Copy link
Author

Thanks for @YannickJadoul for providing the cpp code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment