python - SWIG C++/Python:如何处理抽象类的shared_ptr的std::map

标签 python c++ abstract-class swig stdmap

如何通过以下c++代码使用SWIG处理python中抽象方法的映射:

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可能是导演类。

我的问题:
  • 与该问题关联的最小的.i文件是什么?
  • 我也读到这会导致python / C++棘手的所有权
    问题,例如删除my_B。我如何轻松转移
    从python到C++的“my_B”所有权?

  • 非常感谢你的帮助

    一种。

    最佳答案

    这是一个跟踪构建/销毁的工作示例,以显示共享指针的引用计数正在工作:

    测试

    #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;
    

    测试

    %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>>;
    

    输出:

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

    关于python - SWIG C++/Python:如何处理抽象类的shared_ptr的std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61484768/

    相关文章:

    java - 为什么 AbstractList,AbstractSet 做抽象而不是接口(interface)

    java - 抽象类实现 Cloneable;抽象对象克隆()

    python - Pandas 键列表列和值列表列到字典列表列

    c++ - 本书中的qt示例

    c++ - 抽象类上的模板类

    c++ - QState::assignProperty 不起作用

    c++ - 取消引用迭代器导致 'can not convert' 错误,但它似乎不应该

    python - 使用无缝日期范围作为索引来旋转 Pandas 数据框

    python - 如何使用 Selenium/PhantomJS 列出加载的资源?

    python - 由字母组成的字母