示例代码说明:
struct Base
{
virtual int foo() = 0;
};
struct Derived : public Base
{
virtual int foo()
{
return 42;
}
};
Base* get_base()
{
return new Derived;
}
BOOST_PYTHON_MODULE(libTestMod)
{
py::class_<Base>("Base", py::no_init)
.def("foo", py::pure_virtual(&Base::foo));
py::def("get_base", get_base, py::return_internal_reference<>()); //ignore mem leak
}
尝试了上述代码,但未能编译。
更新: 编译错误:
/path/to/boostlib/boost/1.53.0-0/common/include/boost/python/object/value_holder.hpp:66:11: error: cannot declare field 'boost_1_53_0::python::objects::value_holder<Base>::m_held' to be of abstract type 'Base'
Main.C:59:8: note: because the following virtual functions are pure within 'Base':
Main.C:61:15: note: virtual int Base::foo()
抽象类实际上可以在没有包装器的情况下公开给Boost.Python。 诀窍是用boost::noncopyable定义类,并避免使用纯虚拟方法包装器。
下面是正确的代码(使用Boost.Python 1.47.0和Python 2.7.6进行了测试):
测试:
有关详细信息,当通过} 文档说明:
boost::python::class_
公开类型时,HeldType
默认为公开的类型,并且HeldType
在Python对象中构造。^{因此,
boost::python::class_<Base>
将失败,因为T = Base
和HeldType = Base
,以及Boost.Python将尝试将HeldType
的对象实例化为表示Base
实例的Python对象。这个实例化将失败,因为Base
是一个抽象类。下面是一个完整的示例,显示了
BaseWrap
类的使用。以及它的用法:
可以在Boost.Python中公开抽象类,方法是不使用默认的初始值设定项(
boost::python::no_init
)和不可复制(boost::noncopyable
)。缺少初始值设定项会阻止Python类型从中派生,从而有效地防止重写。另外,^ {CD15}}在C++中实现的实现细节,由^ {CD16> }是无关紧要的。如果Python根本不应该知道foo()
方法,那么省略通过def()
公开它。交互使用:
相关问题 更多 >
编程相关推荐