Note: The corresponding gist is here.
I have an abstract base class and a method that accepts a pointer to the base class, e.g.,
#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
After SWIGging this with
%module mytest
%{
#define SWIG_FILE_WITH_INIT
#include "mytest.hpp"
%}
%include <std_shared_ptr.i>
%shared_ptr(MyBaseClass);
%shared_ptr(Square);
%include "mytest.hpp"
I can create Square
instances and feed them into mytest
from within Python, e.g.,
import mytest
a = mytest.Square()
mytest.mytest(a)
As expected, this will print
1.0
4.0
9.0
I'd now like to derive more classes from MyBaseClass
, but from Python. Unfortunately, simply doing
class Cube(mytest.MyBaseClass):
def __init__(self):
return
def eval(self, x):
return x*x*x
c = Cube()
mytest.mytest(c)
results in the error
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 &'
Any hints?