我有一些第三方C++扩展代码,希望在我的Python代码中使用。所以我开始使用Sigg来帮助它,C++支持得很好。正如SWIG在http://www.swig.org/Doc1.3/SWIGDocumentation.html#Python_directors上所说,它可以支持多态性,所以我使用了以下代码,但是我遇到了一些奇怪的问题。在
我有这样的c++.h代码:
class A
{
public:
virtual void foo(){std::cout<<"A foo"<<endl;};
};
class B
{
public:
A *a = nullptr;
};
extern A *g_a;
我有这样的c++.cpp代码:
^{pr2}$我的.i文件如下:
^{3}$我的py文件是这样的:
import A
class ASub(A.A):
def __init__(self):
super(ASub, self).__init__()
def foo(self):
super(ASub, self).foo()
print "ASub foo"
if __name__ == "__main__":
bb = A.B()
bb.a = ASub()
bb.a.foo() # only print "A foo", but no "ASub foo"
A.cvar.g_a = ASub()
A.cvar.g_a.foo() # this line will give three random results when run in
# serveral times, 1) the python interpreter crashes,
# 2) gives a traceback saying it has no attribute,
# 3) just print "A foo", without "ASub foo"
通常我希望我能得到“阿福”和“阿苏布福”华硕.foo是以各种方式调用的,但它并不像我预期的那样工作。有人能帮我解释一下吗?在
不过,下面的代码是有效的!为什么?在
//c++, which is in module A
void update(A *a)
{
a->foo();
}
//python
my_a = ASub()
A.update(my_a)
上面的代码给出了“A foo”和“ASub foo”。我真的很困惑!在
目前没有回答
相关问题 更多 >
编程相关推荐