SWIG c++ python: 如何处理抽象类的shared_ptr的std::map?

问题描述 投票:1回答:1

如何在python中用SWIG处理抽象方法的映射,从下面的c++代码。

class A : Base {
    virtual int f() = 0;
};

class B : public A {
    int f() { return 10 }; 
}; 

class C : public A {
    int f() { return 20 }; 
}; 

std::map< std::string, std::shared_ptr<A>> my_map; 

在python中,我也想做类似的事情。

my_B = B()
my_map["foo"] = my_B

或者更简单一些

my_map["foo"] = B()

我必须明确A或B可以是导演类,以便使用跨语言多态性。

我的问题是

  1. 与这个问题相关的最小.i文件是什么?
  2. 我还读到,如果例如my_B被删除,这可能会导致python C++棘手的所有者问题。 我如何才能轻松地将 "my_B "的所有权从 python 转移到 C++?

谢谢你的帮助

A.

python c++ abstract-class swig stdmap
1个回答
0
投票

下面是一个工作示例,通过跟踪constructiondestruction来显示共享指针的引用计数是有效的。

test.h

#include <map>
#include <memory>
#include <string>
#include <iostream>

class A {
public:
    virtual int f() = 0;
    A() { std::cout << "A()" << std::endl; }
    virtual ~A() { std::cout << "~A()" << std::endl; }
};

class B : public A {
public:
    int f() { return 10; }
    B() { std::cout << "B()" << std::endl; }
    virtual ~B() { std::cout << "~B()" << std::endl; }
};

class C : public A {
public:
    int f() { return 20; }
    C() { std::cout << "C()" << std::endl; }
    virtual ~C() { std::cout << "~C()" << std::endl; }
};

std::map< std::string, std::shared_ptr<A>> my_map;

test.i

%module test

%{
#include "test.h"
%}

%include <std_map.i>
%include <std_shared_ptr.i>
%include <std_string.i>

// declare all visible shared pointers so SWIG generates appropriate wrappers
// before including the header.
%shared_ptr(A)
%shared_ptr(B)
%shared_ptr(C)

%include "test.h"

// Declare the template instance used so SWIG will generate the wrapper.
%template(Map) std::map<std::string, std::shared_ptr<A>>;

输出: test.h test.i

>>> import test
>>>
>>> m=test.cvar.my_map    # global variables are in module's cvar.
>>> m['foo'] = test.C()
A()
C()
>>> m['foo'].f()
20
>>> del m['foo']  # only reference, so it is freed
~C()
~A()
>>> b = test.B()  # 1st reference
A()
B()
>>> m['bar'] = b  # 2nd reference
>>> del m['bar']  # NOT freed.
>>> del b         # now it is freed.
~B()
~A()
© www.soinside.com 2019 - 2024. All rights reserved.