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

时间:2016-09-01 13:09:30

标签: 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 &'

任何提示?

1 个答案:

答案 0 :(得分:1)

得到它(通过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