gpt4 book ai didi

python - 在C++中访问pybind11 kwargs

转载 作者:行者123 更新时间:2023-12-02 10:28:16 32 4
gpt4 key购买 nike

我在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>()}
};

关于python - 在C++中访问pybind11 kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63398434/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com