python - 从 SWIGged Python 中的 C++ 基类派生

标签 python c++ swig

注意:对应的要点是here .


我有一个抽象基类和一个接受指向基类的指针的方法,例如,

#ifndef MYTEST_HPP
#define MYTEST_HPP

#include <iostream>
#include <memory>

class MyBaseClass {
  public:
    virtual
    double
    eval(const double x) const = 0;
};

class Square: public MyBaseClass {
  public:
    virtual
    double
    eval(const double x) const
    {
      return x*x;
    }
};


void
mytest(const std::shared_ptr<MyBaseClass> & a) {
  std::cout << a->eval(1.0) << std::endl;
  std::cout << a->eval(2.0) << std::endl;
  std::cout << a->eval(3.0) << std::endl;
}

#endif // MYTEST_HPP

用 SWIGging 之后

%module mytest

%{
#define SWIG_FILE_WITH_INIT
#include "mytest.hpp"
%}

%include <std_shared_ptr.i>
%shared_ptr(MyBaseClass);
%shared_ptr(Square);

%include "mytest.hpp"

我可以创建 Square 实例并将它们从 Python 中输入到 mytest 中,例如,

import mytest
a = mytest.Square()
mytest.mytest(a)

正如预期的那样,这将打印

1.0
4.0
9.0

我现在想从 MyBaseClass 中派生更多的类,但是是从 Python 中派生的。不幸的是,只是做

class Cube(mytest.MyBaseClass):
    def __init__(self):
        return

    def eval(self, x):
        return x*x*x

c = Cube()
mytest.mytest(c)

导致错误

Traceback (most recent call last):
  File "../source/test.py", line 14, in <module>
    mytest.mytest(c)
TypeError: in method 'mytest', argument 1 of type 'std::shared_ptr< MyBaseClass > const &'

有什么提示吗?

最佳答案

知道了(通过 https://stackoverflow.com/a/9042139/353337 ):

将导演功能添加到MyBaseClass

%module(directors="1") mytest

%{
#define SWIG_FILE_WITH_INIT
#include "mytest.hpp"
%}

%include <std_shared_ptr.i>
%shared_ptr(MyBaseClass);
%shared_ptr(Square);

%feature("director") MyBaseClass;

%include "mytest.hpp"

并在 Python 中正确初始化类

class Cube(mytest.MyBaseClass):
    def __init__(self):
        mytest.MyBaseClass.__init__(self)
        return

    def eval(self, x):
        return x*x*x

关于python - 从 SWIGged Python 中的 C++ 基类派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39272413/

相关文章:

Python 根据条件创建基于现有列的列

Python Numpy 如何更改数组内的数据类型

c++ - 创建对象并将其插入 vector 的正确方法是什么?

c++ - 自从在 Golang 中删除了一些 C 之后,SWIG for go 是否已经过时了?

python - 如何使用 SWIG 在 Python 中将 operator<< 包装到 __str__?

python - 如何使 plotly 图例跨越两列

python - 自动化无聊的事情 - 逗号代码 : Why doesn't my code work?

c++ - 从 .txt 文件中删除特定行 (C++)

c++ - SDL - 像控制台一样打印文本?

python - 如何编写 C++ 代码以使用 SWIG 在 python 提示符中打印变量值