在Python类(SWIG)中使用从抽象c++类继承的方法
Use method inherited from abtract C++ class in a Python class (SWIG)
我目前正在使用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
方法
相关文章:
- 无法创建抽象类的实例
- 如何定义一个纯抽象基类
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 用pybind11包装C++抽象类时出错
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 抽象类错误,请参阅声明" "是抽象的
- 将自定义函数传递到基抽象类中以延迟执行
- 命名参数习惯用法和(抽象)基类
- 打印抽象对象 c++
- 如何在从抽象基派生的类中实现相同的方法?
- 将包含抽象类和普通类C++包导出到 Python
- C++:处理抽象类中的错误时出现问题
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- C++抽象的字节序是中立的吗?
- 在 C++ 中使用另一个头文件中的抽象类
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- C++:从抽象类重写纯虚拟运算符重载
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 位集元素迭代的抽象