使用 boost.python 为现有库创建 python 绑定时遇到问题。场景如下:
#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");
}
(抱歉,代码块很长,这是我能想到的最小示例。)
您可以看到我必须重写getString()
BaseWrapper 中的方法,以便它可以与 Python 字符串一起使用,并且这部分工作正常:
>>> import testInheritance
>>> base = testInheritance.Base()
>>> base.getString("bla")
Got string: "bla"
>>>
一旦我尝试getString
从以下实例调用,问题就会出现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)
>>>
我可以理解这里出了什么问题,但我不知道如何解决这个问题。我将不胜感激任何帮助!
最好的问候, eDude