Boost Python 和 shared_ptr 向上转换

0 投票
2 回答
928 浏览
提问于 2025-04-16 05:42

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

试试用 Collector.addParent(const BasePtr& parent) 这个方法。

1

好的……在准备真实的示例代码时,我找到了问题的解决办法。问题出在Collector.addParent(BasePtr& parent)这个地方。看起来Boost Python不喜欢把它写成引用。把它改成Collector.addParent(BasePtr parent)就解决了这个问题。谢谢你们的关注。

撰写回答