【发布时间】: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 &'
有什么提示吗?
【问题讨论】: