Python C ++绑定类型为upcast问题

时间:2015-02-19 14:16:01

标签: python c++ swig upcasting

我有一个C ++代码,它依赖于一个大型库(OpenBabel具体),并使用它的一些类作为我的类的基础。该库有自己的使用SWIG创建的Python绑定。我使用'%import'为我的代码构建了带有SWIG的Python绑定。这个库的界面。当我将类传递给Python代码中的库例程时,这很好用。但是,我遇到了从库的例程中检索我的类的问题。

为了澄清这个想法,我将展示一些代码。对于C ++版本

class Derived: public Library::Base 
{
  // blah-blah
  std::string toString();
};

// the library has function, returning Base*
Library::Base* getData();

// In C++ code I siply use
Derived *d = static_cast<Derived*> (getData());
std::cout << d.toString();

现在我想在Python中做同样的事情:

d = getData();
print( d.toString() )

这会导致错误:AttributeError: 'Base' object has no attribute 'toString'

print(d)会产生<Library.Base; proxy of <Swig Object of type 'std::vector< Library::Base * >::value_type' at 0x7f0ff8279a20> >所以这是C ++ Base*

的包装器

我已经找到了关于向上转播的建议:d.__class__ = Derived,但这对我来说很奇怪。而且,它不起作用。

那么我应该如何在Python中进行upcast,或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

如何使用:

print(str(d))