gpt4 book ai didi

c++ - 需要提升 python 显式类型转换

转载 作者:太空狗 更新时间:2023-10-29 19:53:22 26 4
gpt4 key购买 nike

我有混合系统(c++,boost python)。在我的 C++ 代码中有非常简单的层次结构

class Base{...}
class A : public Base{...}
class B : public Base{...}

另外 2 个业务(在 C++ 上)方法

smart_ptr<Base> factory() //this produce instances of A and B
void consumer(smart_ptr<A>& a) //this consumes instance of A

在 python 代码中,我使用 factory 创建 A 的实例并尝试调用消费者方法:

v = factory() #I'm pretty sure that it is A instance
consumer(v)

绝对合理我有异常(exception):

Python argument types in consumer(Base) did not match to C++ signature: consumer(class A{lvalue})

发生这种情况是因为无法告诉 Boost 应该进行一些转换工作。

有什么方法可以指定动态转换行为吗?提前谢谢你。

最佳答案

说到boost::shared_ptr , Boost.Python 通常提供所需的功能。在这种特殊情况下,无需显式提供自定义 to_python转换器,只要模块声明定义 Baseboost::shared_ptr<Base> 持有,并且 Boost.Python 被告知 A继承自 Base .

BOOST_PYTHON_MODULE(example) {
using namespace boost::python;
class_<Base, boost::shared_ptr<Base>,
boost::noncopyable>("Base", no_init);
class_<A, bases<Base>,
boost::noncopyable>("A", no_init);
def("factory", &factory);
def("consumer", &consumer);
}

Boost.Python 目前不支持自定义左值转换器,因为它需要更改核心库。因此,consumer功能要么需要接受 boost:shared_ptr<A>按值或按常量引用。以下任一签名都应该有效:

void consumer(boost::shared_ptr<A> a)
void consumer(const boost::shared_ptr<A>& a)

这是一个完整的例子:

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

class Base
{
public:
virtual ~Base() {}
};

class A
: public Base
{
public:
A(int value) : value_(value) {}
int value() { return value_; };
private:
int value_;
};

boost::shared_ptr<Base> factory()
{
return boost::make_shared<A>(42);
}

void consumer(const boost::shared_ptr<A>& a)
{
std::cout << "The value of object is " << a->value() << std::endl;
}

BOOST_PYTHON_MODULE(example) {
using namespace boost::python;
class_<Base, boost::shared_ptr<Base>,
boost::noncopyable>("Base", no_init);
class_<A, bases<Base>,
boost::noncopyable>("A", no_init);
def("factory", &factory);
def("consumer", &consumer);
}

以及用法:

>>> from example import *
>>> x = factory()
>>> type(x)
<class 'example.A'>
>>> consumer(x)
The value of object is 42
>>>

由于模块声明指定了 BaseA 的基类, Boost.Python 能够解析从 factory() 返回的类型至 example.A .

关于c++ - 需要提升 python 显式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14652136/

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