我想知道在使用A
而不是B
时,下面的std::shared_ptr
和boost::shared_ptr
类如何在python中以多态方式工作?
struct A
{
virtual ~A() {}
};
struct B : A
{
B() {}
virtual ~B() {}
};
void f(const std::shared_ptr<A>& ptr)
{}
BOOST_PYTHON_MODULE(test)
{
class_<A, boost::noncopyable>("A", no_init);
class_<B, std::shared_ptr<B>, bases<A>>("B")
.def(init<>());
def("f", f);
}
我知道必须为boost::get_pointer
定义std::shared_ptr
方法,因此我确保在#include <boost/python.hpp>
之前存在以下行:
namespace boost {
template<class T> const T* get_pointer(const std::shared_ptr<T>& p)
{
return p.get();
}
template<class T> T* get_pointer(std::shared_ptr<T>& p)
{
return p.get();
}
} // namespace boost
现在,在python中我尝试:
>>> from test import *
>>> b = B()
>>> f(b)
Traceback (most recent call last):
File "<console>", line 1, in <module>
ArgumentError: Python argument types in
test.f(B)
did not match C++ signature:
f(std::shared_ptr<A>)
注意:上面的代码适用于boost::shared_ptr
,但我想坚持使用C ++ 11类型。
感谢。
答案 0 :(得分:0)
Boost.Python内置了特殊魔法来识别boost :: shared_ptr。它目前不识别std :: shared_ptr。现在,只需皱眉并使用boost :: shared_ptr。
答案 1 :(得分:0)
我在编写时使用std::shared_ptr
使用get_pointer
与boost :: python IIRC一起工作。 (相关评论为here)。我的猜测是你需要class_<A,std::shared_ptr<A>,...>
,因为这是你的函数作为参数。