如何使用boost :: python从Python抽象基类继承?

时间:2019-02-28 18:02:43

标签: python c++ boost abstract-base-class

我想制作一个类似dict的对象来与c ++ std::map进行接口。在纯Python中,我了解创建dict接口的最佳方法是访问inherit from collections.MutableMapping and override the appropriate methods__getitem____setitem__等)。

但是,就我而言,我想使用map<string, string>连接到C ++中的boost::python

现在我知道可以通过在class_构造函数中指定bases<T>来继承用C ++创建并使用boost注册的另一类。但是,我似乎无法想出让DictInterface类继承自MutableMapping的一种方法,以便利用Abstract Base Class提供的所有其他功能。

#include <map>
#include <boost/python.hpp>

using namespace boost::python;

class DictInterface
{
public:
    DictInterface(std::map<std::string, std::string>& m)
    {
        cpp_map = m;
    }

    std::string getitem(const std::string& key) const
    {
        std::string ret = some_decoding(cpp_map.at(key));
        return ret;
    }

    void setitem(const std::string& key, const std::string& value)
    {
        cpp_map.insert_or_assign(key, some_encoding(value));
    }

    void delitem(const std::string& key)
    {
        if (cpp_map.find(key)) {
            cpp_map.erase(key);
        }
    }

    /* ...More methods... */

private:
    std::map<std::string, std::string>& cpp_map;
}

// Expose to python
void export_DictInterface_h()
{
    class_<DictInterface, /*here is where bases would go*/>
        .def("__getitem__", &DictInterface::getitem)
        .def("__setitem__", &DictInterface::setitem)
        .def("__delitem__", &DictInterface::delitem)
        // ... More method definitions ...
        // Is this where I could inherit from MutableMapping?
    ;
}

0 个答案:

没有答案
相关问题