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
Usage from python
The class is part of a bigger project that runs in C++. There are some properties that need to be set with internal logic. I prefer to keep the setter getter logic on the c++ side and allow python to interface with it. The problem is that I don't know how to provide these bindings through pybind11.