在 Python 类 (SWIG) 中使用从抽象 C++ 类继承的方法 [英] Use method inherited from abtract C++ class in a Python class (SWIG)
问题描述
我目前正在使用 SWIG 使我的主要 C++ 程序中的小模块的实现更容易.类架构如下:
I am currently using SWIG to make the implementation of small modules easier in my main C++ programm. The class architecture is as follow :
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 包装器:
I then generate the swig wrappers using the following command :
swig -python -c++ file.i
并像这样编译 .so :
and compile the .so like this :
g++ -fPIC -shared -o _foo.so file_wrap.cxx -I/usr/include/python2.7 -lpython2.7
当我尝试运行 python 脚本时,出现以下错误:
And when I try to run the python script I get the following error :
# 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 *'
# _
这表明使用纯方法是有效的,但我不能使用已在 .hpp 文件中定义的方法.
That shows that the use of the pure method is working but I can't use the one already defined in the .hpp file.
我尝试阅读 SWIG 文档,我看到的关于抽象类和继承的唯一内容是 34.4.7 C++ 类 和 34.4.8 C++ 继承.而且我看不到任何提及此类案件的内容.
I have tried to read the SWIG documentation and the only things I see about abstract class and inheritance are 34.4.7 C++ Classes and 34.4.8 C++ Inheritance. And I can't see anything mentionning a case like that.
推荐答案
你忘记调用Bar
的父类的__init__
方法.用这个替换你的 __init__
方法:
You have forgotten to call the __init__
method of the parent class of Bar
. Replace your __init__
method with this:
class Bar(foo.Foo):
def __init__(self):
super(Bar,self).__init__()
这应该让您的 Bar
类知道 Foo
方法.
This should let your Bar
class know about the Foo
method.
这篇关于在 Python 类 (SWIG) 中使用从抽象 C++ 类继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!