kyy
kyy

Reputation: 321

swig python wrap c++ vector of pointers to polymorphic types

I have 2 classes("Foo", "Bar") which are derived from base class "Base" as below.

class Base{
public:
    virtual void basemethod() = 0 ;
};

class Base: public Foo{

    virtual void basemethod() ;
    void foo();
};

class Base: public Bar{
    virtual void basemethod() ;
    void bar();
};

And there is another class which createds instances of these classes as below

class Entity{
    std::vector<std::shared_ptr<Base> > Get();
};

I have below idl file but in this case, in python code, i can not access real type information

%include "std_vector.i"
%include <std_shared_ptr.i>

%template(MyVector) std::vector<std::shared_ptr<Base> >;

Is it possible to wrap this interface in swig so below code in python works as expected?

entity = Entity()
vec = entity.Get()

if isinstance(vec[0], Bar):
    print("this is a Bar!")

if isinstance(vec[1], Foo):
    print("this is a Foo!")

Upvotes: 3

Views: 500

Answers (1)

Jens Munk
Jens Munk

Reputation: 4725

You are almost there...

base.hpp

#pragma once

class Base{
 public:
  virtual void basemethod() = 0;
  virtual ~Base() = default;
  virtual const char* name() = 0;
};

derivatives.hpp

#pragma once

#include "base.hpp"

class Foo : public Base {
  virtual void basemethod();
  void foo();
  const char* name();
};

class Bar : public Base {
  virtual void basemethod();
  void bar();
  const char* name();
};

entity.hpp

#include <memory>
#include <vector>
#include "base.hpp"

class Entity {
 public:
  static std::vector<std::shared_ptr<Base> > Get();
};

derivatives.cpp

#include "derivatives.hpp"

void Foo::basemethod() {
}
void Foo::foo() {
}

const char* Foo::name() {
  static char name[] = "Foo";
  return name;
}

void Bar::basemethod() {
}
void Bar::bar() {
}

const char* Bar::name() {
  static char name[] = "Bar";
  return name;
}

entity.cpp

#include "entity.hpp"
#include "derivatives.hpp"

std::vector<std::shared_ptr<Base> > Entity::Get() {
    std::vector<std::shared_ptr<Base> > vec;
    std::shared_ptr<Base> base = std::make_shared<Foo>();
    vec.push_back(base);
    return vec;
}

example.i

%module example
%{
  #include "base.hpp"
  #include "derivatives.hpp"
  #include "entity.hpp"
%}

%include "std_vector.i"
%include "std_shared_ptr.i"

%shared_ptr(Base);
%shared_ptr(Foo);
%shared_ptr(Bar);

%template(BaseVector) std::vector<std::shared_ptr<Base> >;

%include "base.hpp"
%include "derivatives.hpp"
%include "entity.hpp"

%extend Base {
%pythoncode %{
  def __instancecheck__(self, other):
    return self.name() == other.name()
%}
};

After compilation, you can do the following in Python

import example
hmm = example.Entity_Get()
isinstance(hmm[0], example.Foo())

Adding an entry of the Bar class to the vector should be straight forward.

Upvotes: 2

Related Questions