gpt4 book ai didi

python - swig python 包装指向多态类型的指针的 C++ vector

转载 作者:太空狗 更新时间:2023-10-29 22:54:35 25 4
gpt4 key购买 nike

我有 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> >;

是否可以将此接口(interface)包装在 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!")

最佳答案

你快到了......

基础.hpp

#pragma once

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

衍生品.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();
};

实体.hpp

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

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

导数.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;
}

实体.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;
}

例子.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 类的条目添加到 vector 应该很简单。

关于python - swig python 包装指向多态类型的指针的 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com