Sample code for 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)
;
}
example code to test it in Python console:
import hello
p = hello.createParentA()
c = hello.Collector()
c.addParent(p)
Initial post with fake code:
I'm having some problems in having Boost Python to upcast a shared_ptr from Python.
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 >();
}
And in Python we do:
from PythonModule import *
p = ParentA()
c = Collector()
c.addParent(p) # Fails here because no upcast is happening.
Any ideas on how I can make this work?
Compiled on VS2008, with BOOST 1.44 and Python 3.0.
Thanks,