gpt4 book ai didi

c++ - Boost Python 和 shared_ptr 向上转换

转载 作者:行者123 更新时间:2023-11-28 08:26:17 25 4
gpt4 key购买 nike


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。

谢谢,

最佳答案

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

关于c++ - Boost Python 和 shared_ptr 向上转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com