我目前正在使用 SWIG 来简化我的主 C++ 程序中小模块的实现。类架构如下:
foo.hpp :
class Foo
{
public:
virtual int pureFunc() = 0;
int func() { return (42); }
};
文件.i :
%module(directors="1") foo
%feature("director") Foo;
%{
#include "foo.hpp"
%}
%include "foo.hpp"
文件.py :
import sys
sys.path.append('.')
import foo
class Bar(foo.Foo):
def __init__(self):
pass
def pureFunc(self):
return 21
lol = Bar()
print lol.pureFunc()
print lol.func()
然后我使用以下命令生成 swig 包装器:
swig -python -c++ file.i
然后像这样编译.so:
g++ -fPIC -shared -o _foo.so file_wrap.cxx -I/usr/include/python2.7 -lpython2.7
当我尝试运行 python 脚本时,出现以下错误:
# python file.py
21
Traceback (most recent call last):
File "file.py", line 13, in <module>
print lol.func()
File "/home/volent/dev/CPP/cython/foo.py", line 84, in func
def func(self): return _foo.Foo_func(self)
TypeError: in method 'Foo_func', argument 1 of type 'Foo *'
# _
这表明使用 pure 方法是有效的,但我不能使用已经在 .hpp 文件中定义的方法。
我已经尝试阅读 SWIG 文档,但我看到的关于抽象类和继承的唯一内容是 34.4.7 C++ Classes和 34.4.8 C++ Inheritance .而且我看不到任何提及此类案例的内容。
最佳答案
您忘记调用Bar
的父类的__init__
方法。将您的 __init__
方法替换为:
class Bar(foo.Foo):
def __init__(self):
super(Bar,self).__init__()
这应该让您的 Bar
类知道 Foo
方法。
关于c++ - 在 Python 类 (SWIG) 中使用从抽象 C++ 类继承的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840706/