swig python包装指向多态类型的指针的c ++向量

时间:2019-03-02 21:08:09

标签: python c++ swig

我有2个类(“ Foo”,“ Bar”),它们是从基类“ Base”派生的,如下所示。

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();
};

还有另一个类,可以如下创建这些类的实例

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

我在idl文件下面,但是在这种情况下,在python代码中,我无法访问实型信息

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

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

是否可以将此接口包装在swig中,以便python中的以下代码按预期工作?

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!")

1 个答案:

答案 0 :(得分:1)

你快到了...

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()
%}
};

编译后,您可以在Python中执行以下操作

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

直接将Bar类的条目添加到向量中。

相关问题