使用boost python扩展一个公开的类

时间:2013-11-15 14:07:10

标签: boost-python

我想扩展一个已经暴露给python的类。例如:

摘录1:

class_<DataValueContainer, DataValueContainer::Pointer>( "DataValueContainer" )
    .def( "__len__", &DataValueContainer::Size )
    .def( VariableIndexingPython<DataValueContainer, Variable<std::string> >() )
    .def( VariableIndexingPython<DataValueContainer, Variable<int> >() )
    .def( VariableIndexingPython<DataValueContainer, Variable<double> >() )
    .def( self_ns::str( self ) )
    ;

现在我想在不同的地方扩展python类DataValueContainer,例如:

摘录2:

class_<DataValueContainer, DataValueContainer::Pointer>
    .def( VariableIndexingPython<DataValueContainer, Variable<MyObject> >() )

是否可以使用boost.python来做到这一点?之所以我想这样做是因为代码片段1在现有代码的内核中,我不愿修改它。

祝你好运

1 个答案:

答案 0 :(得分:0)

据我所知,如果不对代码段1进行一些细微修改或重新实现boost::python::class_的部分内容,则无法做到这一点。当实例化类型为boost::python::class_的对象时,类型初始化和注册发生在Boost.Python的内部。使用相同类型和参数实例化class_将有效地覆盖先前的类对象。

在Python中,问题类似于重新定义的类型。在下面的示例中,spam标识符用于一种类型,然后与另一种类型关联:

>>> class spam:
...     def action1(self): pass
... 
>>> # Redefines spam type.
... class spam:
...     def action2(self): pass
... 
>>> print hasattr(s, "action1")
False
>>> print hasattr(s, "action2")
True

而不是通过其标识符扩展spam类型:

>>> class spam:
...     def action1(self): pass
... 
>>> # Extend spam type.
... def action2(s): pass
... 
>>> spam.action2 = action2
>>> s = spam()
>>> print hasattr(s, "action1")
True
>>> print hasattr(s, "action2")
True

Boost.Python示例与Python示例完全等效。在此代码段中,spam标识符被修改为指向新类型,因为实例化了新的class_实例。

#include <boost/python.hpp>

class spam {};
void action1(spam& self) {}
void action2(spam& self) {}

BOOST_PYTHON_MODULE(example)
{
  typedef boost::python::class_<spam> spam_class_type;
  spam_class_type("spam")
    .def("action1", &action1)
    ;

  // Redefines spam type. 
  spam_class_type("spam")
    .def("action2", &action1)
    ;
}

及其用法:

>>> import example
__main__:1: RuntimeWarning: to-Python converter for spam already 
            registered; second conversion method ignored.
>>> s = example.spam()
>>> print hasattr(s, "action1")
False
>>> print hasattr(s, "action2")
True

要扩展Boost.Python中的类型,只需在同一个class_实例上运行:

#include <boost/python.hpp>

class spam {};
void action1(spam& self) {}
void action2(spam& self) {}

BOOST_PYTHON_MODULE(example)
{
  typedef boost::python::class_<spam> spam_class_type;
  spam_class_type spam_ = spam_class_type("spam");
  spam_
    .def("action1", &action1)
    ;

  // Extend spam type.
  spam_
    .def("action2", &action2)
    ;
}

及其用法:

>>> import example
>>> s = example.spam()
>>> print hasattr(s, "action1")
True
>>> print hasattr(s, "action2")
True