在 SWIGged Python 中派生自 C++ 基础 class

Derive from C++ base class in SWIGged Python

注:对应的gist是here.


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

#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

痛饮之后
%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 中导出更多 classes,但从 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 &'

有什么提示吗?

知道了(通过 ):

将导演功能添加到 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
class Cube(mytest.MyBaseClass):
    def __init__(self):
        mytest.MyBaseClass.__init__(self)
        return

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