在 C++ 中访问 pybind11 kwargs

Access pybind11 kwargs in C++

我在 python 中有以下 kwargs:

interface_dict = {'type':['linear'], 'scope':['ascendant'], height:[-0.4272,0.4272], length:[27.19], 'flag':[True]}
interface.py_interface(**interface_dict)

我在 C++ 中使用 pybind11 来访问这些 python 值。我正在尝试将这些值存储在像这样的变体多映射中:

void py_interface(py::kwargs kwarg){
    std::multimap<std::string, std::variant<float, bool, int, std::string>> kwargs = {
        {"type", (*(kwarg["type"]).begin()).cast<std::string>()}, 
        {"scope", (*(kwarg["scope"]).begin()).cast<std::string>()}, 
        {"height", (*(kwarg["height"]).begin()).cast<float>()}, 
        {"length", (*(kwarg["length"]).begin()).cast<float>()}, 
        {"flag", (*(kwarg["flag"]).begin()).cast<bool>()} 
    }; 
    kwargs.insert(std::pair<std::string, std::variant<float, bool, int, std::string>>("height", /* question how do I access the second value of height to store it here */)); 

我的问题是如何访问高度的第二个值 (0.4272)。我尝试使用 .end() 但出现错误:

kwargs.insert(std::pair<std::string, std::variant<float, bool, int, std::string>>("height",(*(kwarg["height"]).end()).cast<float>())); //error unable to cast Python instance to C++ type

有人可以帮助我吗?

您可以使用 py::sequence 按索引访问项目。只需确保元素存在于给定索引下:

    std::multimap<std::string, std::variant<float, bool, int, std::string>> kwargs = {
        {"type", (*(kwarg["type"]).begin()).cast<std::string>()},
        {"scope", (*(kwarg["scope"]).begin()).cast<std::string>()},
        {"height", py::sequence(kwarg["height"])[1].cast<float>()},
        {"length", (*(kwarg["length"]).begin()).cast<float>()},
        {"flag", (*(kwarg["flag"]).begin()).cast<bool>()}
    };

另一种选择是增加您通过 begin() 调用创建的迭代器:

    std::multimap<std::string, std::variant<float, bool, int, std::string>> kwargs = {
        {"type", (*(kwarg["type"]).begin()).cast<std::string>()},
        {"scope", (*(kwarg["scope"]).begin()).cast<std::string>()},
        {"height", (*(kwarg["height"].begin()++)).cast<float>()},
        {"length", (*(kwarg["length"]).begin()).cast<float>()},
        {"flag", (*(kwarg["flag"]).begin()).cast<bool>()}
    };