2013-02-04 51 views
2

如何访问已注册给定C++类的boost :: python :: class_对象?我正在导入一个boost :: python模块,它为boost :: property_tree :: ptree定义了一个包装器,但我想向此包装器定义添加其他方法。当我尝试创建一个新的包装器时,Boost Python抱怨已经声明了一个处理器,并且忽略了我的新定义。修改Boost Python包装类?

任何想法?

+1

难道是添加的方法来使用python纸上出现问题?这应该是非常简单的。 – daramarak

+0

哦,是啊!完全忘了我可以做到这一点。我会试一试... – fredbaba

+0

完美工作。我决定回答我自己的问题并接受它。希望别人会觉得它有用。 – fredbaba

回答

3

遵循daramarak的建议,以及Boost Python教程Extending Wrapped Objects In Python,我在python中扩展了这个类。 Python,因此Boost :: Python在绑定成员函数和第一个参数是对象引用(或指针)的函数之间几乎没有区别。因此,你可以在C定义一个函数++像这样:

bool ptree__contains(boost::property_tree::ptree* self, const std::string& key) { 
    return self->find(key)!=self->not_found(); 
} 

再增加导入的类在Python像这样:

from other_module import ptree 
from my_module import ptree__contains 

# The __contains__ method is a special api function 
# that enables "foo in bar" boolean test statements 
ptree.__contains__ = ptree__contains 

test_ptree = ptree() 
test_ptree.put("follow.the.yellow.brick.road", "OZ!") 

print "follow.the.yellow.brick.road" in test_ptree 
# > true 

我说我隆胸的代码我模块的__init__.py,使得我的模块的任何导入都会自动将所需的方法添加到外部对象。我定义了一个修改这个类的函数,叫做这个函数,然后删除它来清理我的名字空间。或者,您可以从__all__列表中排除此功能,以防止其被from module import *语句导出。奇迹般有效!再次感谢daramarak。

+0

很好的解决方案和有据可查的+1。我们需要更多的boost :: python答案。 – daramarak

0

我有一个类似的问题,但有一点不同:由于类导出定义在我自己的代码中,因此我能够更改第一次调用boost::python::class_的部分。

如果这也是你的情况可能的解决方案可能是这样的:

static auto ptree_class_ = boost::python::class_<ptree> ("ptree"); 

// somewhere later in your code: 
ptree_class_.def("contains", &ptree__contains); 

这样就不需要额外的Python代码 - 全部是用C++完成。

在这里,你可以找到我原来的解决方案:https://stackoverflow.com/a/30622038/4184258