Как я могу наследовать от абстрактного базового класса Python, используя boost::python?

Я хотел бы сделать dict-подобный объект для взаимодействия с C++ std::map, В чистом питоне я понимаю лучший способ создать dict интерфейс должен унаследовать от collections.MutableMapping и переопределить соответствующие методы(__getitem__,__setitem__, так далее.).

В моем случае, однако, я хотел бы подключиться кmap<string, string>в C++ с помощьюboost::python,

Теперь я знаю, что можно создать подкласс другого класса, который был создан в C++ и зарегистрирован с использованием boost, указавbases<T> в class_ конструктор. Тем не менее, я не могу найти способ для моего DictInterface класс для наследования MutableMapping чтобы воспользоваться всеми дополнительными функциями, предоставляемыми абстрактным базовым классом.

#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 ответов

Другие вопросы по тегам