在Python类(SWIG)中使用从抽象c++类继承的方法

Use method inherited from abtract C++ class in a Python class (SWIG)

本文关键字:抽象 c++ 方法 继承 Python SWIG      更新时间:2023-10-16

我目前正在使用SWIG,以便在我的主c++程序中更容易实现小模块。类架构如下:

foo.hpp:

class Foo
{
public:
  virtual int pureFunc() = 0;
  int func() { return (42); }
};

文件。我:

%module(directors="1") foo
%feature("director") Foo;
%{
  #include "foo.hpp"
%}
%include "foo.hpp"

file.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++类和34.4.8 c++继承。我没有看到任何提到这样的情况

您忘记调用Bar父类的__init__方法了。将您的__init__方法替换为:

class Bar(foo.Foo):
    def __init__(self):
        super(Bar,self).__init__()

这应该让你的Bar类知道Foo方法