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

cvanelteren commented May 12, 2020

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.

from nest_cppclass import Test

# init class
test  = Test()

# allow setter
test.someProperty = 3

# allow getter
if test.someProperty == 3:
  # do something

@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