std :: shared_ptr +纯虚拟+使用Boost.python在python中覆盖

问题描述

在下面的用例中,我想重写python中的纯虚拟类,并将shared_ptr传递给C ++类。我尝试了以下操作,但无法正常工作。

#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/python/class.hpp>
#include <boost/python/module_init.hpp>
#include <boost/python/def.hpp>
#include <boost/python/call_method.hpp>
#include <boost/ref.hpp>
#include <memory>
#include <boost/utility.hpp>
#include <iostream>
#include <memory>
using namespace std;

class Vector : public std::enable_shared_from_this<Vector> {
    public:
        Vector() {}
        virtual void prints()
        {  std::cout << "Vector" << std::endl;    }
};

struct PyVector : Vector,boost::python::wrapper<Vector> {
    PyVector(): Vector() {}
    void prints() { this->get_override("prints")(); }
};

class Foo {
    public:
        Foo(boost::shared_ptr<Vector> vec) : _vec(vec){}
        boost::shared_ptr<Vector> _vec;
        void prints() {
            _vec -> prints();
        }
};

#include <boost/python.hpp>
using namespace boost::python;
    
BOOST_PYTHON_MODULE(Virtually) {

    class_<Vector,boost::shared_ptr<Vector>,PyVector>("vector",init<>());

    class_<Foo,boost::shared_ptr<Foo>>("foo",init<boost::shared_ptr<Vector>>())
        .def("prints",&Foo::prints);

}

对于打击python代码,它给出了错误的值


In [3]: class MyVector(m.vector):
   ...: 
   ...:     def prints(self):
   ...:         print("MyVector")
   ...:         
   ...:     def __del__(self):
   ...:         print("I was deleted")

In [4]: x = MyVector()

In [5]: fo = m.foo(x)

In [6]: fo.prints()
Vector // It should have printed MyVector

问题:

  1. 为什么我会看到这种行为?我覆盖的方法无法识别?
  2. 我想通过纯虚拟类来增强此功能(即,Vector.prints必须设置为纯虚拟)。我该怎么办?
  3. 我想使用std :: shared_ptr代替boost :: shared_ptr

如何使用Boost.python实现它们。如果不能提升python哪个工具,我该如何实现?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)