-
I have a beginners question: If I have these two classes: class vectorBase{
public:
std::vector<double> values(){
return m_vec;
}
int size(){
return m_vec.size();
}
protected:
std::vector<double> m_vec;
};
class Vector : public vectorBase {
public:
Vector(){
m_vec = {1.,2.,3.};
}
virtual ~Vector(){}
}; This pybind code correctly returns the vector: PYBIND11_MODULE(pybindTest, m) {
py::class_<vectorBase, std::shared_ptr<vectorBase>>(m,"vectorBase");
py::class_<Vector, std::shared_ptr<Vector>,vectorBase>(m,"Vector")
.def(py::init<>())
.def("values", &vectorBase::values)
.def("size", &vectorBase::size);
} while this code does not (vector too long): PYBIND11_MODULE(pybindTest, m) {
py::class_<vectorBase, std::shared_ptr<vectorBase>>(m,"vectorBase")
.def("values", &vectorBase::values)
.def("size", &vectorBase::size);
py::class_<Vector, std::shared_ptr<Vector>,vectorBase>(m,"Vector")
.def(py::init<>());
} In Python: vec = pybindTest.Vector()
values = vec.values() I'm just wondering whether the last approach is possible/could be fixed, because in a similar example I want to bind many derived classes and it would be convenient to wrap the members of the base class only once and have access then in each derived class. Thanks alot for looking at my example! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
In fact your code is OK, there is a problem with C++ base provided by you. Remove In [2]: import mymodule
In [3]: a = mymodule.Vector()
In [4]: a.size()
Out[4]: 3
In [5]: a.values()
Out[5]: [1.0, 2.0, 3.0]
In [6]: dir(mymodule.Vector)
Out[6]:
['__class__',
'__delattr__',
'__dir__',
# ...
'__subclasshook__',
'size',
'values']
In[7]: help(my module.Vector.size)
Help on instancemethod in module mymodule:
size(...)
size(self: mymodule.vectorBase) -> int |
Beta Was this translation helpful? Give feedback.
In fact your code is OK, there is a problem with C++ base provided by you. Remove
virtual ~Vector(){}
from your class and keep bindings as is. Actually if you inherit class -- it also reflects this in Python. Here, you may see that after calling todir(Vector)
it shows both methods and usevectorBase
as self: