c++ - 在 Boost.Python 中沮丧

标签 c++ python boost boost-python

编辑:将“upcast”更正为“downcast”。

当我使用的类来自 C++ 时,我正在尝试找出在 Python 中进行向下转换的最佳方法。如果我在 C++ 中定义了两个类:

struct Base
{
    int foo()
    {
        return 7;
    }
};

struct Derived : Base
{
    int bar()
    {
        return 42;
    }
};

还有一个函数

Base baz()
{
    return Derived();
}

如果我在 Python 中尝试

der = baz()
print der.foo()
print der.bar()

调用 bar() 失败,因为 Python 只知道 Base 中的函数。

我的解决方案是向 Derived 添加另一个函数:

Derived * fromBase(Base * b)
{
    return reinterpret_cast<Derived *>(b);
}

如果我随后将 Python 脚本的第一行更改为 der = Derived.fromBase(baz()),脚本将按预期工作。

但是,我使用 reinterpret_cast 来完成这项工作这一事实似乎是非常错误的。有没有更好的向下转换方法,不需要使用像 reinterpret_cast 这样危险的东西?如果没有,fromBase() 的返回政策应该是什么?

在任何人问之前,是的,沮丧是必要的。这就是我必须使用的库的工作方式。

编辑:

我正在寻找像这样的 C# 代码的东西:

Base b = new Derived();
Derived d = b as Derived;
if (d != null)
    ...

最佳答案

Base baz()
{
    return Derived();
}

从返回类型可以看出,这返回一个Base对象,不是Derived对象。所以没有什么可以向下转换(而不是向上转换)的。所以你首先需要解决这个问题。

更重要的是,您是对的,reinterpret_cast 在这种情况下绝对是可疑的。 dynamic_cast 实际上是用于向下转换的工具。

更根本的是,您应该问问自己为什么需要沮丧。您的示例代码可能是合成的,不能代表您的确切问题,但为什么 baz 不应该返回 Derived


这是您的代码段的等效内容:

Derived d;
Base& b = d;
if(Base* p = dynamic_cast<Derived*>(&b))
    // okay; b is actually an instance of Derived

关于c++ - 在 Boost.Python 中沮丧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12222824/

相关文章:

c++ - boost 时间戳 UDP 数据包

c++ - 在 Linux 上使用 CMake 将 boost 链接到共享库

c++ - 从文件中读取数据 C++

c++ - 在iOS上执行pthread_cancel时,堆中的内存会被释放吗?

c++ - 无法安装 R 包 "BH"

python - 如何以行协议(protocol)格式显示 csv 文件?

python - 我可以将 xvfb 与 AWS Lambda 一起使用吗?

c++ - 'C' 程序 : multidimensional array issue

c++ - rank 函数的 Rcpp 糖

python - 如何使用 pymongo 更新集合中的所有文档