boost python_Boost Python:多态容器?

I have a method (or function) which returns a reference to a list of polymorphic objects:

class A {

};

class B : public A {

};

std::list<:shared_ptr> >& getList();

How do I expose such a function in boost::python so that when iterating on the list in python, I would see the different types of As and Bs ?

解决方案

First, make sure your classes are indeed polymorphic (i.e. they have at least one virtual function or a virtual destructor). Your example above doesn't, though I'm sure your real use case does. Without that none of Boost.Python's RTTI-based machinery for polymorphism will work.

Then, if you've exposed both classes with Boost.Python and registered shared_ptr converters for them:

#include

namespace bp = boost::python;

BOOST_PYTHON_MODULE(example) {

bp::class_("A");

bp::register_ptr_to_python< boost::shared_ptr >();

bp::class_< B, bp::bases >("B");

bp::register_ptr_to_python< boost::shared_ptr >();

}

...that's all you need to do to make sure Python only ever sees the most-derived type. There's no need to do anything special to ensure A is casted to B when possible.

That still leaves the question of how to wrap a function that returns a container. The simplest is probably to use the indexing suite included with Boost.Python:

There are other options floating around the web (including a "version 2" of the indexing suite that is better in many respects, but isn't included with Boost.Python), but for simple problems this is probably the most convenient.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值