【问题标题】:Derive from C++ base class in SWIGged Python从 SWIGged Python 中的 C++ 基类派生
【发布时间】:2016-09-01 13:09:30
【问题描述】:

注意:对应的要点是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 &'

有什么提示吗?

【问题讨论】:

    标签: python c++ swig


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 2012-12-10
      • 2020-03-04
      • 1970-01-01
      • 2011-12-07
      • 2019-01-17
      相关资源
      最近更新 更多