Add Member Functions To A Boost Python Class After The Fact?
Solution 1:
obj
doesn't have a member function named def
, but class_
does. class_
inherits from object
, which is why that assignment works, but you don't have to do that. The following works fine:
auto obj = class_<MyClass>("MyClass")
.def("SomeFunc", &MyClass::SomeFunc)
;
// now obj is an instance of py::class_<MyClass> instead of py::object
obj.def("SomeOtherFunc", &MyClass::SomeOtherFunc);
The fact that you never name the class_
instance may distract from the fact that this is a simple constructor. You could have also written the above as:
class_<MyClass> obj("MyClass");
obj.def("SomeFunc", &MyClass::SomeFunc);
obj.def("SomeOtherFunc", &MyClass::SomeOtherFunc);
You don't have to define everything in one go.
Bonus points if someone can explain exactly what
def
is doing and why I don't need commas in between defs.
def
is a member function on the class template class_
. It has a bunch of overloads, all of which returns a reference to self:
template <classInit> class_& def(Init );
template <classF> class_& def(charconst*, Fn );
template <classFn, classA1> class_& def(charconst*, Fn, A1 );
// etc.
That's why you can chain them. Each call independently sets up the internal machinery to expose that function to python and just returns *this
. I don't know what you would need commas for.
Post a Comment for "Add Member Functions To A Boost Python Class After The Fact?"