1

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?

1 Answer 1

1

Got it (via https://stackoverflow.com/a/9042139/353337):

Add the director feature to 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"

and properly initialize the class in Python

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

    def eval(self, x):
        return x*x*x
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.