Boost Python和shared_ptr upcast

时间:2010-10-18 23:52:16

标签: c++ python boost


dll / pyd的示例代码:

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

class Base
{
public: Base() {}
public: int getValue() { return 1; }
};

typedef boost::shared_ptr<Base> BasePtr;

class ParentA : public Base
{   
public: ParentA() : Base() {}
};

typedef boost::shared_ptr<ParentA> ParentAPtr;

class Collector
{
public: Collector() {}
public: void addParent(BasePtr& parent)
{
    std::cout << parent->getValue() << std::endl;
}
};

typedef boost::shared_ptr<Collector> CollectorPtr;

ParentAPtr createParentA()
{
return ParentAPtr(new ParentA());
};

BOOST_PYTHON_MODULE(hello)
{
boost::python::class_<Base, BasePtr, boost::noncopyable>("Base",
        boost::python::no_init)
        .def("getValue", &Base::getValue)
;

boost::python::class_<ParentA, ParentAPtr, boost::python::bases<Base>>("ParentA")
;

boost::python::implicitly_convertible< ParentAPtr, BasePtr >();

boost::python::def("createParentA", createParentA);

boost::python::class_<Collector, CollectorPtr>("Collector")
    .def("addParent", &Collector::addParent)
;
}

在Python控制台中测试它的示例代码:

import hello
p = hello.createParentA()
c = hello.Collector()
c.addParent(p)

伪造代码的初始帖子:

我在使用Boost Python从Python上传一个shared_ptr时遇到了一些问题。

class Base() {...};
class ParentA(): public Base {...};
class ParentB(): public Base {...};

typedef boost::shared_ptr<Base> BasePtr;
typedef boost::shared_ptr<Parent> ParentPtr;

class Collector() 
{
  void addParent(BasePtr& parent) {...}
}
typedef boost::shared_ptr<Collector> CollectorPtr;

BOOST_PYTHON_MODULE(PythonModule)
{
 boost::python::class_<Collector, CollectorPtr>("Collector")
  .def("addParent", &Collector::addParent)


 boost::python::class_<Base, BasePtr, boost::noncopyable>("Base", 
            boost::python::no_init)
 ...
 ;

 boost::python::class_<ParentA, ParentAPtr, 
            boost::python::bases<Base>>("ParentA", 
        boost::python::init<>())
 ...
 ;

 boost::python::implicitly_convertible< ParentAPtr, BasePtr >();
}

在Python中我们做:

from PythonModule import *
p = ParentA()
c = Collector()
c.addParent(p) # Fails here because no upcast is happening. 

关于如何使这项工作的任何想法?

在VS2008上编译,使用BOOST 1.44和Python 3.0。

谢谢,

2 个答案:

答案 0 :(得分:1)

好的......在准备真正的示例代码时,我提出了解决方案。问题出在Collector.addParent(BasePtr&amp; parent)中。似乎Boost Python不喜欢它作为参考。将它更改为Collector.addParent(BasePtr parent)修复它。感谢您对此进行调查。

答案 1 :(得分:0)

尝试Collector.addParent(const BasePtr&amp; parent)