2016-09-01 61 views
1

注意:相應的要點是here從SWIGged Python中的C++基類派生


我有一個抽象基類,並且接受一個指向基類的方法,例如,

#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在此之後可以創建Square實例並將它們從w中輸入mytest ithin的Python,例如,

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

正如預期的那樣,這將打印

1.0 
4.0 
9.0 

我現在想從MyBaseClass獲得更多的類,但在Python。不幸的是,簡單地做錯誤

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 &' 

任何提示

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

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

c = Cube() 
mytest.mytest(c) 

結果?

回答

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