【发布时间】:2014-12-10 02:55:55
【问题描述】:
我使用 SWIG 向 Python 公开了以下 c++ 类(简化):
struct Component
{
virtual void update();
}
struct DerivedComponent : public Component
{
void update() { cout << "DerivedComponent::update()" << endl; }
void speak() { cout << "DerivedComponent::speak()" << endl; }
}
class Entity
{
public:
Component* component(const std::string& class_name)
{
return m_components[class_name];
}
private:
std::unordered_map<std::string, Component*> m_components;
}
现在,在 Python 中,我可以在实体实例上成功调用 component("DerivedComponent").update()。但是,我无法调用component("DerivedComponent").speak(),因为component("DerivedComponent") 返回的类型报告为<class 'module.Component'>。
我显然需要向下转换component() 函数的结果,以便调用DerivedComponent 中定义的方法。我曾希望 Swig 能够像我相信的 Boost.Python 那样执行自动向下转换。
没有在 c++ 中定义一大堆类型转换函数并将它们暴露给 Python,有没有更好的使用 Swig 或 Python 进行向下转换的解决方案?我有哪些选择?
【问题讨论】:
-
你不能在 C++ 中调用该方法而不进行向下转换,那么你为什么认为你可以在 Python 中侥幸逃脱呢?您需要在 C++ 中定义类型转换函数并公开它们。
-
@MarkTolonen 这并不是说我认为我可以在不进行类型转换的情况下逃脱。正如 Flexo 的回答所示,我只是希望有一种方法可以使流程自动化。