gpt4 book ai didi

python - 将派生类传递给在 SWIG Python 中采用基类的函数

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:03 26 4
gpt4 key购买 nike

我使用 Python 3.3 和 SWIG 2.0.10 将派生类传递给采用基类的函数。

C# 正在使用相同的 SWIG .i 文件并且运行良好。但是,在 Python 中,SWIG 报告没有接受派生类型的 C++ 方法——只有接受基类型的方法。该声明是正确的,但我需要传递派生类型并让 SWIG 直接调用,就好像它是基本类型一样。

派生类型在 C++ 中不存在。它仅存在于 Python(和 C#)中。但是,我们启用了 Controller ,并且如前所述,它在 C# 中运行良好。

Python 2.6 和 2.7 中的结果相同。

C++

class Base {};
// Note: there is NO "class Derived" in C++.
void f(Base* a) { ... }

python

class Derived(Base): pass

x = Derived()
f(x) # SWIG runtime error - In C++ there is no f(Derived*) - there is only f(Base*)

最佳答案

问题是在 Derived 类中我没有正确调用 Base.__init__()。

一旦我解决了这个问题,Swig 中的多态性就可以正常工作了。

class Derived(Base):
def __init__(self):
super(Derived, self).__init__()

关于python - 将派生类传递给在 SWIG Python 中采用基类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17984978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com