<boost/python/instance_holder.hpp> 提供了类instance_holder
,它是包含包装类的C ++实例的类型的基类。
Class template instance_holder
instance_holder
是一个抽象基类,其具体派生类在其Python对象包装器中保存C ++类实例。 为了允许C ++类包装器在Python中进行多重继承,每个这样的Python对象都包含一个instance_holders链。 当调用包装的C ++类的__init__
函数时,将使用其install ()
函数创建一个新的instance_holder
实例并将其安装在Python对象中。 从instance_holder
派生的每个具体类必须提供一个holds ()
实现,它允许Boost.Python查询它所持有的类型。 为了支持保持类型的包装构造函数,该类还必须提供构造函数,这些构造函数可以接受引用拥有的Python对象的初始PyObject *
参数,并将其余参数转发给保持类型的构造函数。 需要初始参数才能在Python中启用虚函数覆盖,并且可能会被忽略,具体取决于特定的instance_holder
子类。
namespace boost { namespace python
{
class instance_holder : noncopyable
{
public:
// destructor
virtual ~instance_holder();
// instance_holder modifiers
void install(PyObject* inst) throw();
// instance_holder observers
virtual void* holds(type_info) = 0;
};
}}
virtual ~instance_holder();
作用
销毁对象实体
void install(PyObject* inst) throw();
条件
inst
是包装的C ++类类型的Python实例,或者是从包装的C ++类类型派生的类型。
作用
将新实例安装在Python对象的持有实例链的头部。
异常
没有
virtual void *holds(type_info x) = 0;
返回
指向由x
描述的类型的对象的指针,如果* this
包含这样的对象,否则为0。
以下是Boost.Python用于包装智能指针所包含的类的实例持有者模板的简化版本:
template <class SmartPtr, class Value>
struct pointer_holder : instance_holder
{
// construct from the SmartPtr type
pointer_holder(SmartPtr p)
:m_p(p)
// Forwarding constructors for the held type
pointer_holder(PyObject*)
:m_p(new Value())
{
}
template<class A0>
pointer_holder(PyObject*,A0 a0)
:m_p(new Value(a0))
{
}
template<class A0,class A1>
pointer_holder(PyObject*,A0 a0,A1 a1)
:m_p(new Value(a0,a1))
{
}
...
private: // required holder implementation
void* holds(type_info dst_t)
{
// holds an instance of the SmartPtr type...
if (dst_t == python::type_id<SmartPtr>())
return &this->m_p;
// ...and an instance of the SmartPtr's element_type, if the
// pointer is non-null
return python::type_id<Value>() == dst_t ? &*this->m_p : 0;
}
private: // data members
SmartPtr m_p;
};