简体   繁体   English

提升Python和shared_ptr的向量

[英]Boost Python and vectors of shared_ptr

I've read how to expose normal vectors to python in boost python, but I want to know how to expose and make use of a vector. 我已经阅读了如何在boost python中将普通向量暴露给python,但我想知道如何公开和使用向量。 For instance, I have a vector of shared_ptrs as follows: 例如,我有一个shared_ptrs向量,如下所示:

std::vector<shared_ptr<StatusEffect> > Effects;

Based on the material for exposing vectors, I should be able to expose this type of class. 基于暴露向量的材料,我应该能够暴露这种类。 What I want to know is how can I actually add to it? 我想知道的是我怎样才能真正添加​​它? How do I create instances of shared_ptr<StatusEffect> since I don't have access to new, and the shared_ptr can point to multiple derived types making adding a static creation method to each class a little tedious. 如何创建shared_ptr<StatusEffect>实例,因为我无权访问new,而shared_ptr可以指向多个派生类型,这使得为每个类添加静态创建方法有点乏味。

Does anyone have some pointers or can suggest how to do this? 有没有人有一些指示或可以建议如何做到这一点? Finding good example for boost::python for what I want to do has been abit tricky 为我想做的事情找到boost :: python的好例子已经变得非常棘手了

Thanks in advance 提前致谢

struct A {
    int index;
    static shared_ptr<A> create () { return shared_ptr<A>(new A); }
    std::string   hello  () { return "Just nod if you can hear me!"; }
};

BOOST_PYTHON_MODULE(my_shared_ptr)
{
    class_<A, shared_ptr<A> >("A",boost::python::init<>())
        .def("create",&A::create )
        .staticmethod("create")
        .def("hello",&A::hello)
        .def_readonly("index",&A::index)
    ;

    boost::python::class_<std::vector<shared_ptr<A>>>("PyVec")
    .def(boost::python::vector_indexing_suite<std::vector<shared_ptr< A>>,true >());

}

The argument of ",true" is important! “,真实”的论点很重要!

You can partially bind boost::shared_ptr<StatusEffect> , omitting the construction just fine with Boost.Python (use boost::python::no_init ). 你可以部分绑定boost::shared_ptr<StatusEffect> ,用Boost.Python省略构造(使用boost::python::no_init )。 To have a similar mechanism with std::shared_ptr<StatusEffect> you will also need to define a boost::get_pointer<T>() free function with T = std::shared_ptr<U> as explained in this other SO thread . 要使用与std::shared_ptr<StatusEffect>类似的机制,您需要使用T = std::shared_ptr<U>定义boost::get_pointer<T>()自由函数,如此其他SO线程中所述 Here is a sketch of a workable solution: 这是一个可行解决方案的草图:

#include <boost/python.hpp>
#include <memory>
...

namespace boost { 
  template<class T> T* get_pointer(std::shared_ptr<T> p) { return p.get(); } 
}

BOOST_PYTHON_MODULE(yourmodule) {

  using namespace boost::python;

  class_<StatusEffect, std::shared_ptr<StatusEffect>, boost::noncopyable>("StatusEffect", no_init);

  class_<std::vector<std::shared_ptr<StatusEffect> > >("StatusEffectVector")
    .def(boost::python::vector_indexing_suite<std::vector<shared_ptr<StatusEffect>>, true>());

}

有关示例,请参阅指针和智能指针

你提到每个类的创建方法(构造函数)会有点乏味,但我认为这就是你需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM