Boost.Python中的向下广播
Downcast in Boost.Python
EDIT:将"upcast"更正为"downstast"。
当我使用的类来自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())
,那么该脚本将按预期工作。
然而,我使用repret_cast来完成这项工作的事实似乎是非常错误的。有没有一种更好的方式来进行向下转换,而不需要使用像interpret_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
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- 使用Pybind11向Python公开Eigen::张量
- Python str to C++ to Python str
- 如何使用Python从C++中读取谷物序列化数据
- 如何在C++中使用pybind11加载一个pickle python列表
- 如何在c++中使用system()来运行包含空格的python脚本
- python集合的C++等价物是什么.计数器
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 从python调用openMP共享库时,未定义opnMP函数
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 如何将真正的字符串从python c-api转换为python脚本
- Boost.Python中的向下广播