I have run into a problem when creating python bindings for an existing library with boost.python. The scenario is as follows:
#include<boost/python.hpp>
namespace bp = boost::python;
struct Base {
std::stringstream _myString;
Base() { };
Base(const Base& base) { _myString<<base._myString.str(); }
void getString(std::stringstream& some_string) {
_myString.str("");
_myString<<some_string.str();
std::cout<<"Got string: \""<<_myString.str()<<"\""<<std::endl;
}
};
struct BaseWrapper : Base,
bp::wrapper<Base>
{
BaseWrapper() :
Base(),
bp::wrapper<Base>() { };
BaseWrapper(const Base& base) :
Base(base),
bp::wrapper<Base>() { };
void getString(bp::object pyObj) {
std::string strLine = bp::extract<std::string>(pyObj);
std::stringstream sstrLine;
sstrLine<<strLine;
Base::getString(sstrLine);
}
};
struct Derived : Base
{
Derived() : Base() { };
Derived(const Derived& derived) : Base() { _myString<<derived._myString.str(); };
};
struct DerivedWrapper : Derived,
bp::wrapper<Derived>
{
DerivedWrapper() :
Derived(),
bp::wrapper<Derived>() { };
DerivedWrapper(const Derived derived) :
Derived(derived),
bp::wrapper<Derived>() { };
};
BOOST_PYTHON_MODULE(testInheritance){
bp::class_<BaseWrapper>("Base")
.def("getString", &BaseWrapper::getString);
bp::class_<DerivedWrapper, bp::bases<Base> >("Derived");
}
(Sorry for the long code block, it was the minimum example I could think of.)
You can see that I had to override getString() method in the BaseWrapper so that it would work with Python strings and this part works fine:
>>> import testInheritance
>>> base = testInheritance.Base()
>>> base.getString("bla")
Got string: "bla"
>>>
The problem appears as soon as I try to call getString from a instance of Derived:
>>> derived = testInheritance.Derived()
>>> derived.getString("bla")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
Base.getString(Derived, str)
did not match C++ signature:
getString(BaseWrapper {lvalue}, boost::python::api::object)
>>>
I can understand what is going wrong here, but I have no idea how to fix that. I would appreciate any help!
Best Regards, eDude